~ubuntu-branches/ubuntu/natty/moin/natty-updates

« back to all changes in this revision

Viewing changes to MoinMoin/support/werkzeug/contrib/wrappers.py

  • Committer: Bazaar Package Importer
  • Author(s): Jonas Smedegaard
  • Date: 2008-06-22 21:17:13 UTC
  • mto: This revision was merged to the branch mainline in revision 18.
  • Revision ID: james.westby@ubuntu.com-20080622211713-inlv5k4eifxckelr
ImportĀ upstreamĀ versionĀ 1.7.0

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# -*- coding: utf-8 -*-
2
 
"""
3
 
    werkzeug.contrib.wrappers
4
 
    ~~~~~~~~~~~~~~~~~~~~~~~~~
5
 
 
6
 
    Extra wrappers or mixins contributed by the community.  These wrappers can
7
 
    be mixed in into request objects to add extra functionality.
8
 
 
9
 
    Example::
10
 
 
11
 
        from werkzeug import Request as RequestBase
12
 
        from werkzeug.contrib.wrappers import JSONRequestMixin
13
 
 
14
 
        class Request(RequestBase, JSONRequestMixin):
15
 
            pass
16
 
 
17
 
    Afterwards this request object provides the extra functionality of the
18
 
    :class:`JSONRequestMixin`.
19
 
 
20
 
    :copyright: (c) 2009 by the Werkzeug Team, see AUTHORS for more details.
21
 
    :license: BSD, see LICENSE for more details.
22
 
"""
23
 
from werkzeug.exceptions import BadRequest
24
 
from werkzeug.utils import cached_property
25
 
from werkzeug._internal import _decode_unicode
26
 
try:
27
 
    from simplejson import loads
28
 
except ImportError:
29
 
    from json import loads
30
 
 
31
 
 
32
 
class JSONRequestMixin(object):
33
 
    """Add json method to a request object.  This will parse the input data
34
 
    through simplejson if possible.
35
 
 
36
 
    :exc:`~werkzeug.exceptions.BadRequest` will be raised if the content-type
37
 
    is not json or if the data itself cannot be parsed as json.
38
 
    """
39
 
 
40
 
    @cached_property
41
 
    def json(self):
42
 
        """Get the result of simplejson.loads if possible."""
43
 
        if 'json' not in self.environ.get('CONTENT_TYPE', ''):
44
 
            raise BadRequest('Not a JSON request')
45
 
        try:
46
 
            return loads(self.data)
47
 
        except Exception:
48
 
            raise BadRequest('Unable to read JSON request')
49
 
 
50
 
 
51
 
class ProtobufRequestMixin(object):
52
 
    """Add protobuf parsing method to a request object.  This will parse the
53
 
    input data through `protobuf`_ if possible.
54
 
 
55
 
    :exc:`~werkzeug.exceptions.BadRequest` will be raised if the content-type
56
 
    is not protobuf or if the data itself cannot be parsed property.
57
 
 
58
 
    .. _protobuf: http://code.google.com/p/protobuf/
59
 
    """
60
 
 
61
 
    #: by default the :class:`ProtobufRequestMixin` will raise a
62
 
    #: :exc:`~werkzeug.exceptions.BadRequest` if the object is not
63
 
    #: initialized.  You can bypass that check by setting this
64
 
    #: attribute to `False`.
65
 
    protobuf_check_initialization = True
66
 
 
67
 
    def parse_protobuf(self, proto_type):
68
 
        """Parse the data into an instance of proto_type."""
69
 
        if 'protobuf' not in self.environ.get('CONTENT_TYPE', ''):
70
 
            raise BadRequest('Not a Protobuf request')
71
 
 
72
 
        obj = proto_type()
73
 
        try:
74
 
            obj.ParseFromString(self.data)
75
 
        except Exception:
76
 
            raise BadRequest("Unable to parse Protobuf request")
77
 
 
78
 
        # Fail if not all required fields are set
79
 
        if self.protobuf_check_initialization and not obj.IsInitialized():
80
 
            raise BadRequest("Partial Protobuf request")
81
 
 
82
 
        return obj
83
 
 
84
 
 
85
 
class RoutingArgsRequestMixin(object):
86
 
    """This request mixin adds support for the wsgiorg routing args
87
 
    `specification`_.
88
 
 
89
 
    .. _specification: http://www.wsgi.org/wsgi/Specifications/routing_args
90
 
    """
91
 
 
92
 
    def _get_routing_args(self):
93
 
        return self.environ.get('wsgiorg.routing_args', (()))[0]
94
 
 
95
 
    def _set_routing_args(self, value):
96
 
        if self.shallow:
97
 
            raise RuntimeError('A shallow request tried to modify the WSGI '
98
 
                               'environment.  If you really want to do that, '
99
 
                               'set `shallow` to False.')
100
 
        self.environ['wsgiorg.routing_args'] = (value, self.routing_vars)
101
 
 
102
 
    routing_args = property(_get_routing_args, _set_routing_args, doc='''
103
 
        The positional URL arguments as `tuple`.''')
104
 
    del _get_routing_args, _set_routing_args
105
 
 
106
 
    def _get_routing_vars(self):
107
 
        rv = self.environ.get('wsgiorg.routing_args')
108
 
        if rv is not None:
109
 
            return rv[1]
110
 
        rv = {}
111
 
        if not self.shallow:
112
 
            self.routing_vars = rv
113
 
        return rv
114
 
 
115
 
    def _set_routing_vars(self, value):
116
 
        if self.shallow:
117
 
            raise RuntimeError('A shallow request tried to modify the WSGI '
118
 
                               'environment.  If you really want to do that, '
119
 
                               'set `shallow` to False.')
120
 
        self.environ['wsgiorg.routing_args'] = (self.routing_args, value)
121
 
 
122
 
    routing_vars = property(_get_routing_vars, _set_routing_vars, doc='''
123
 
        The keyword URL arguments as `dict`.''')
124
 
    del _get_routing_vars, _set_routing_vars
125
 
 
126
 
 
127
 
class ReverseSlashBehaviorRequestMixin(object):
128
 
    """This mixin reverses the trailing slash behavior of :attr:`script_root`
129
 
    and :attr:`path`.  This makes it possible to use :func:`~urlparse.urljoin`
130
 
    directly on the paths.
131
 
 
132
 
    Because it changes the behavior or :class:`Request` this class has to be
133
 
    mixed in *before* the actual request class::
134
 
 
135
 
        class MyRequest(ReverseSlashBehaviorRequestMixin, Request):
136
 
            pass
137
 
 
138
 
    This example shows the differences (for an application mounted on
139
 
    `/application` and the request going to `/application/foo/bar`):
140
 
 
141
 
        +---------------+-------------------+---------------------+
142
 
        |               | normal behavior   | reverse behavior    |
143
 
        +===============+===================+=====================+
144
 
        | `script_root` | ``/application``  | ``/application/``   |
145
 
        +---------------+-------------------+---------------------+
146
 
        | `path`        | ``/foo/bar``      | ``foo/bar``         |
147
 
        +---------------+-------------------+---------------------+
148
 
    """
149
 
 
150
 
    @cached_property
151
 
    def path(self):
152
 
        """Requested path as unicode.  This works a bit like the regular path
153
 
        info in the WSGI environment but will not include a leading slash.
154
 
        """
155
 
        path = (self.environ.get('PATH_INFO') or '').lstrip('/')
156
 
        return _decode_unicode(path, self.charset, self.encoding_errors)
157
 
 
158
 
    @cached_property
159
 
    def script_root(self):
160
 
        """The root path of the script includling a trailing slash."""
161
 
        path = (self.environ.get('SCRIPT_NAME') or '').rstrip('/') + '/'
162
 
        return _decode_unicode(path, self.charset, self.encoding_errors)