joonis Logo

Python server-side KSS library

kss.py [10.38 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
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
########################################################################
#
#  kss.py - Server-side KSS library
#
#  Copyright (c) 2013 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.
#
########################################################################

"""
"""
import os
import re
import json
from xml.dom.minidom import getDOMImplementation
dom = getDOMImplementation()

__all__ = ['KSSRules', 'KSSResponse']


class KSSRules(object):
    """KSS rule collector for server-side actions."""

    def __init__(self, base_url=''):
        if base_url and not base_url.endswith('/'):
            base_url = base_url + '/'
        self.base_url = base_url
        self.rules = []

    def add(self_, selector_, url_, **kwargs_):
        """Add a new KSS rule to the collector.

        Keyword arguments:
        selector_ -- the selector including event type (eg. "#element:click")
        url_      -- the URL to the action script (absolute or relative)

        Extra named keyword args are used to add action parameters.
        Keywords with a prefix of "evt_" are added as event parameters.

        Example:
        rules.add("a:click", "/kss/action",
            dest="nodeAttr(href)",
            target="nodeAttr(target)",
            foo="kssAttr(bar, true)",
            evt_preventdefault=True,
            )
        """
        # Make sure we have an event type
        if selector_.find(':') < 0:
            raise ValueError('Missing event type in selector "%s"' % selector_)
        # Prepare parameters
        for key, value in kwargs_.items():
            if type(value) in (bool, int, long, float):
                value = str(value).lower()
            if not (value and isinstance(value, str)):
                raise ValueError('Invalid value for parameter "%s"' % key)
            kwargs_[key] = value
        # Prepare the action URL
        if not url_.startswith('/'):
            url_ = self_.base_url + url_
        # Create an action name
        name = url_.split('?')[0].split('/')[-1]
        name = re.sub('[^A-Za-z0-9]', '_', name)
        # Finally add the rule
        self_.rules.append({
            'name': name,
            'selector': selector_,
            'url': url_,
            'params': kwargs_,
            })

    def render(self):
        """Render and return the KSS rules."""
        kss = []
        for rule in self.rules:
            kss.append('%(selector)s {' % rule)
            kss.append('\taction-server: %(name)s;' % rule)
            kss.append('\t%(name)s-kssUrl: "%(url)s";' % rule)
            evt_args = []
            for key, value in rule['params'].items():
                if key.startswith('evt_'):
                    evt_args.append('\t%s: %s;' % (key.replace('_', '-'), value))
                else:
                    kss.append('\t%s-%s: %s;' % (rule['name'], key, value))
            kss = kss + evt_args
            kss.append('}\n')
        return '\n'.join(kss)


class KSSCommand(object):
    """Represents a KSS command.

    It is not meant to be used directly! You get an instance
    via the 'add_command' method of a KSSResponse object.
    """
    # Required by Zope
    __allow_access_to_unprotected_subobjects__ = 1

    def __init__(self, name, selector='', selector_type=''):
        self.name = name
        self.selector = selector
        self.selector_type = selector_type
        self.params = {}

    def set_param(self, name, value):
        """Set a parameter of the KSS command."""
        self.params[name] = value

    def set_params(self, params):
        """Set more parameters of the KSS command via dictionary."""
        self.params.update(params)


class KSSResponse(object):
    """Represents a KSS response (XML or JSON)."""

    # Required by Zope
    __allow_access_to_unprotected_subobjects__ = 1

    def __init__(self, format='xml', encoding='utf-8'):
        self.format = format.lower()
        self.encoding = encoding
        self.commands = []

    def add_command(self_, name_, selector_='', selector_type_='', **kwargs_):
        """Add and return a new KSS command.

        Parameter arguments can be passed in via named keyword args.
        """
        cmd = KSSCommand(name_, selector_, selector_type_)
        if kwargs_:
            cmd.set_params(kwargs_)
        self_.commands.append(cmd)
        return cmd

    def render(self):
        """Render and return the KSS response body."""
        if self.format == 'xml':
            doc = dom.createDocument(None, 'kukit', None)
            kukit = doc.documentElement
            commands = doc.createElement('commands')
            kukit.appendChild(commands)
            for cmd in self.commands:
                command = doc.createElement('command')
                command.setAttribute('name', cmd.name)
                command.setAttribute('selector', cmd.selector)
                command.setAttribute('selectorType', cmd.selector_type)
                commands.appendChild(command)
                for key, value in cmd.params.items():
                    param = doc.createElement('param')
                    param.setAttribute('name', key)
                    if not isinstance(value, unicode):
                        value = str(value).decode(self.encoding)
                    # CDATASection does not take account of strings
                    # that contains the character sequence ']]>'.
                    value = value.replace(']]>', ']]]]>>')
                    for value in value.split(']]>'):
                        cdata = doc.createCDATASection(value)
                        param.appendChild(cdata)
                    command.appendChild(param)
            return doc.toxml(self.encoding)
        elif self.format == 'json':
            obj = {'commands': []}
            for command in self.commands:
                params = {}
                for key, value in command.params.items():
                    if not isinstance(value, unicode):
                        value = str(value).decode(self.encoding)
                    params[key] = value
                obj['commands'].append({
                    'name': command.name,
                    'selector': command.selector,
                    'selectorType': command.selector_type,
                    'params': params,
                    })
            return json.dumps(obj, encoding=self.encoding)
        else:
            raise ValueError('Unknown format "%s"' % self.format)

    @property
    def content_type(self):
        """Return the content type including the used charset."""
        if self.format == 'xml':
            content_type = 'text/xml'
        elif self.format == 'json':
            content_type = 'application/json'
        else:
            raise ValueError('Unknown format "%s"' % self.format)
        return '%s; charset=%s' % (content_type, self.encoding)

    def send(self):
        """Send the KSS response out to the browser.

        The behavior of this method depends on the web framework
        you are using. You could overwrite it in a subclass or
        via monkeypatch.
        """
        raise NotImplementedError('Overwrite this method in a subclass')

    def __call__(self, environ, start_response):
        """Kind of WSGI implementation."""
        body = self.render()
        start_response('200 OK', [
            ('Content-Type', self.content_type),
            ('Content-Length', len(body)),
            ])
        return [body]


# CGI implementation

if os.environ.get('GATEWAY_INTERFACE'):
    # Overwrite KSSResponse.send
    def _send_kss_response(self):
        body = self.render()
        print 'Content-Type: %s' % self.content_type
        print 'Content-Length: %i' % len(body)
        print
        print body
    KSSResponse.send = _send_kss_response


# Zope implementation
# Put this file into the Extensions folder of your Zope instance.

if os.environ.get('ZOPE_HOME'):
    # Overwrite KSSResponse.send
    def _send_kss_response(self, REQUEST):
        body = self.render()
        REQUEST.RESPONSE.setHeader('Content-Type', self.content_type)
        REQUEST.RESPONSE.setHeader('Content-Length', len(body))
        REQUEST.RESPONSE.write(body)
    KSSResponse.send = _send_kss_response

    def create_kss_response(format='xml', encoding='utf-8'):
        """KSSResponse factory for use as an External Method in Zope"""
        return KSSResponse(format, encoding)

    def generate_kss_rules(folder, recursive=True):
        """Create KSS rules from Python Scripts in a given folder.

        We will misuse the title property as the CSS selector. Each
        function parameter must have a default value (str, num or bool)
        that is used as the argument of the corresponding KSS parameter.

        All Python Scripts with an id starting with 'kss_' will be
        processed. Use this function as an External Method in Zope.
        """
        rules = KSSRules('/')
        for id in folder.objectIds('Script (Python)'):
            script = folder[id]
            selector = script.title
            if not script.id.startswith('kss_'):
                continue
            try:
                # params() returns the script parameters as string:
                # eg. "foo='nodeAttr(id)', evt_preventdefault=True"
                params = eval('dict(%s)' % script.params(),
                            {'__builtins__': None},
                            {'dict': dict, 'True': True, 'False': False})
            except Exception, err:
                raise ValueError('Invalid parameter list of script "%s"' % script.id)
            rules.add(selector, script.absolute_url(relative=True), **params)
        kss = '\n/* %s */\n\n%s' % (folder.title_or_id(), rules.render())
        if recursive:
            for id in folder.objectIds('Folder'):
                kss = kss + generate_kss_rules(folder[id], True)
        return kss

Can I
  help you?


Just drop me a line at
giraffe@joonis.de