File: cornice.py

package info (click to toggle)
python-wsme 0.6-3
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 956 kB
  • ctags: 1,831
  • sloc: python: 8,452; makefile: 138
file content (168 lines) | stat: -rw-r--r-- 5,387 bytes parent folder | download | duplicates (3)
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
"""
WSME for cornice


Activate it::

    config.include('wsme.cornice')


And use it::

    @hello.get()
    @wsexpose(Message, wsme.types.text)
    def get_hello(who=u'World'):
        return Message(text='Hello %s' % who)
"""
from __future__ import absolute_import

import inspect
import sys

import wsme
from wsme.rest import json as restjson
from wsme.rest import xml as restxml
import wsme.runtime
import wsme.api
import functools

from wsme.rest.args import (
    args_from_args, args_from_params, args_from_body, combine_args
)


class WSMEJsonRenderer(object):
    def __init__(self, info):
        pass

    def __call__(self, data, context):
        response = context['request'].response
        response.content_type = 'application/json'
        if 'faultcode' in data:
            if 'orig_code' in data:
                response.status_code = data['orig_code']
            elif data['faultcode'] == 'Client':
                response.status_code = 400
            else:
                response.status_code = 500
            return restjson.encode_error(None, data)
        obj = data['result']
        if isinstance(obj, wsme.api.Response):
            response.status_code = obj.status_code
            if obj.error:
                return restjson.encode_error(None, obj.error)
            obj = obj.obj
        return restjson.encode_result(obj, data['datatype'])


class WSMEXmlRenderer(object):
    def __init__(self, info):
        pass

    def __call__(self, data, context):
        response = context['request'].response
        if 'faultcode' in data:
            if data['faultcode'] == 'Client':
                response.status_code = 400
            else:
                response.status_code = 500
            return restxml.encode_error(None, data)
        response.content_type = 'text/xml'
        return restxml.encode_result(data['result'], data['datatype'])


def get_outputformat(request):
    df = None
    if 'Accept' in request.headers:
        if 'application/json' in request.headers['Accept']:
            df = 'json'
        elif 'text/xml' in request.headers['Accept']:
            df = 'xml'
    if df is None and 'Content-Type' in request.headers:
        if 'application/json' in request.headers['Content-Type']:
            df = 'json'
        elif 'text/xml' in request.headers['Content-Type']:
            df = 'xml'
    return df if df else 'json'


def signature(*args, **kwargs):
    sig = wsme.signature(*args, **kwargs)

    def decorate(f):
        args = inspect.getargspec(f)[0]
        with_self = args[0] == 'self' if args else False
        f = sig(f)
        funcdef = wsme.api.FunctionDefinition.get(f)
        funcdef.resolve_types(wsme.types.registry)

        @functools.wraps(f)
        def callfunction(*args):
            if with_self:
                if len(args) == 1:
                    self = args[0]
                    request = self.request
                elif len(args) == 2:
                    self, request = args
                else:
                    raise ValueError("Cannot do anything with these arguments")
            else:
                request = args[0]
            request.override_renderer = 'wsme' + get_outputformat(request)
            try:
                args, kwargs = combine_args(funcdef, (
                    args_from_args(funcdef, (), request.matchdict),
                    args_from_params(funcdef, request.params),
                    args_from_body(funcdef, request.body, request.content_type)
                ))
                wsme.runtime.check_arguments(funcdef, args, kwargs)
                if funcdef.pass_request:
                    kwargs[funcdef.pass_request] = request
                if with_self:
                    args.insert(0, self)

                result = f(*args, **kwargs)
                return {
                    'datatype': funcdef.return_type,
                    'result': result
                }
            except:
                try:
                    exception_info = sys.exc_info()
                    orig_exception = exception_info[1]
                    orig_code = getattr(orig_exception, 'code', None)
                    data = wsme.api.format_exception(exception_info)
                    if orig_code is not None:
                        data['orig_code'] = orig_code
                    return data
                finally:
                    del exception_info

        callfunction.wsme_func = f
        return callfunction
    return decorate


def scan_api(root=None):
    from cornice.service import get_services
    for service in get_services():
        for method, func, options in service.definitions:
            wsme_func = getattr(func, 'wsme_func')
            basepath = service.path.split('/')
            if basepath and not basepath[0]:
                del basepath[0]
            if wsme_func:
                yield (
                    basepath + [method.lower()],
                    wsme_func._wsme_definition
                )


def includeme(config):
    import pyramid.wsgi
    wsroot = wsme.WSRoot(scan_api=scan_api, webpath='/ws')
    wsroot.addprotocol('extdirect')
    config.add_renderer('wsmejson', WSMEJsonRenderer)
    config.add_renderer('wsmexml', WSMEXmlRenderer)
    config.add_route('wsme', '/ws/*path')
    config.add_view(pyramid.wsgi.wsgiapp(wsroot.wsgiapp()), route_name='wsme')