joonis Logo

Python server-side KSS library

kss.py [2.17 KB]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
########################################################################
#
#  kss.py - Server-side KSS library
#
#  Copyright (c) 2017 joonis new media
#  Author: Thimo Kraemer <thimo.kraemer@joonis.de>
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#  MA 02110-1301, USA.
#
########################################################################

"""
Usage:

// Create a response instance
kss = KSSResponse();

// Add a command
kss.add_command('setNodeAttr', '#my-selector',
    name='foo',
    value='bar',
    )

// Or via dynamic method
kss.setNodeAttr('#my-selector', 
    name='foo',
    value='bar',
    )

// Commands that do not require a selector
kss.add_command('alert', message='Hello!')

// Or via dynamic method
kss.alert(message='Hello!')

// Return the KSS response as JSON
return str(kss)

// Or return it within an RPC service
return kss.response
"""

import json
from functools import partial

__all__ = ['KSSResponse']

class KSSResponse(object):
    
    def __init__(self, encoding='utf-8'):
        self.encoding = encoding
        self.response = {'commands': []}
    
    def add_command(self, _action, _selector=None, **_params):
        self.response['commands'].append({
            'action': _action,
            'selector': _selector,
            'params': _params,
            })
        
    def __getattr__(self, name):
        if name.startswith('_'):
            raise AttributeError(name)
        return partial(self.add_command, name)
        
    def __str__(self):
        return json.dumps(self.response, encoding=self.encoding)

Can I
  help you?


Just drop me a line at
giraffe@joonis.de