|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +# Copyright (c) 2012, Cenobit Technologies, Inc. http://cenobit.es/ |
| 3 | +# All rights reserved. |
| 4 | +import re |
| 5 | +import StringIO |
| 6 | +from inspect import getargspec |
| 7 | +from functools import wraps |
| 8 | + |
| 9 | +from collections import OrderedDict |
| 10 | + |
| 11 | +from flask import request, jsonify |
| 12 | + |
| 13 | +from flask_jsonrpc.site import jsonrpc_site |
| 14 | +from flask_jsonrpc.types import Object, Number, Boolean, String, Array, Nil, Any |
| 15 | +from flask_jsonrpc.exceptions import (Error, ParseError, InvalidRequestError, |
| 16 | + MethodNotFoundError, InvalidParamsError, |
| 17 | + ServerError, RequestPostError, |
| 18 | + InvalidCredentialsError, OtherError) |
| 19 | + |
| 20 | +default_site = jsonrpc_site |
| 21 | +KWARG_RE = re.compile( |
| 22 | + r'\s*(?P<arg_name>[a-zA-Z0-9_]+)\s*=\s*(?P<arg_type>[a-zA-Z]+)\s*$') |
| 23 | +SIG_RE = re.compile( |
| 24 | + r'\s*(?P<method_name>[a-zA-Z0-9._]+)\s*(\((?P<args_sig>[^)].*)?\)' |
| 25 | + r'\s*(\->\s*(?P<return_sig>.*))?)?\s*$') |
| 26 | + |
| 27 | + |
| 28 | +class JSONRPCTypeCheckingUnavailable(Exception): |
| 29 | + pass |
| 30 | + |
| 31 | +def _type_checking_available(sig='', validate=False): |
| 32 | + if not hasattr(type, '__eq__') and validate: # and False: |
| 33 | + raise JSONRPCTypeCheckingUnavailable( |
| 34 | + 'Type checking is not available in your version of Python ' |
| 35 | + 'which is only available in Python 2.6 or later. Use Python 2.6 ' |
| 36 | + 'or later or disable type checking in %s' % sig) |
| 37 | + |
| 38 | +def _validate_arg(value, expected): |
| 39 | + """Returns whether or not ``value`` is the ``expected`` type. |
| 40 | + """ |
| 41 | + if type(value) == expected: |
| 42 | + return True |
| 43 | + return False |
| 44 | + |
| 45 | +def _eval_arg_type(arg_type, T=Any, arg=None, sig=None): |
| 46 | + """Returns a type from a snippit of python source. Should normally be |
| 47 | + something just like 'str' or 'Object'. |
| 48 | + |
| 49 | + arg_type the source to be evaluated |
| 50 | + T the default type |
| 51 | + arg context of where this type was extracted |
| 52 | + sig context from where the arg was extracted |
| 53 | + |
| 54 | + Returns a type or a Type |
| 55 | + """ |
| 56 | + try: |
| 57 | + T = eval(arg_type) |
| 58 | + except Exception, e: |
| 59 | + raise ValueError('The type of %s could not be evaluated in %s for %s: %s' % |
| 60 | + (arg_type, arg, sig, str(e))) |
| 61 | + else: |
| 62 | + if type(T) not in (type, Type): |
| 63 | + raise TypeError('%s is not a valid type in %s for %s' % |
| 64 | + (repr(T), arg, sig)) |
| 65 | + return T |
| 66 | + |
| 67 | +def _parse_sig(sig, arg_names, validate=False): |
| 68 | + """Parses signatures into a ``OrderedDict`` of paramName => type. |
| 69 | + Numerically-indexed arguments that do not correspond to an argument |
| 70 | + name in python (ie: it takes a variable number of arguments) will be |
| 71 | + keyed as the stringified version of it's index. |
| 72 | + |
| 73 | + sig the signature to be parsed |
| 74 | + arg_names a list of argument names extracted from python source |
| 75 | + |
| 76 | + Returns a tuple of (method name, types dict, return type) |
| 77 | + """ |
| 78 | + d = SIG_RE.match(sig) |
| 79 | + if not d: |
| 80 | + raise ValueError('Invalid method signature %s' % sig) |
| 81 | + d = d.groupdict() |
| 82 | + ret = [(n, Any) for n in arg_names] |
| 83 | + if 'args_sig' in d and type(d['args_sig']) is str and d['args_sig'].strip(): |
| 84 | + for i, arg in enumerate(d['args_sig'].strip().split(',')): |
| 85 | + _type_checking_available(sig, validate) |
| 86 | + if '=' in arg: |
| 87 | + if not type(ret) is OrderedDict: |
| 88 | + ret = OrderedDict(ret) |
| 89 | + dk = KWARG_RE.match(arg) |
| 90 | + if not dk: |
| 91 | + raise ValueError('Could not parse arg type %s in %s' % (arg, sig)) |
| 92 | + dk = dk.groupdict() |
| 93 | + if not sum([(k in dk and type(dk[k]) is str and bool(dk[k].strip())) |
| 94 | + for k in ('arg_name', 'arg_type')]): |
| 95 | + raise ValueError('Invalid kwarg value %s in %s' % (arg, sig)) |
| 96 | + ret[dk['arg_name']] = _eval_arg_type(dk['arg_type'], None, arg, sig) |
| 97 | + else: |
| 98 | + if type(ret) is OrderedDict: |
| 99 | + raise ValueError('Positional arguments must occur ' |
| 100 | + 'before keyword arguments in %s' % sig) |
| 101 | + if len(ret) < i + 1: |
| 102 | + ret.append((str(i), _eval_arg_type(arg, None, arg, sig))) |
| 103 | + else: |
| 104 | + ret[i] = (ret[i][0], _eval_arg_type(arg, None, arg, sig)) |
| 105 | + if not type(ret) is OrderedDict: |
| 106 | + ret = OrderedDict(ret) |
| 107 | + return (d['method_name'], |
| 108 | + ret, |
| 109 | + (_eval_arg_type(d['return_sig'], Any, 'return', sig) |
| 110 | + if d['return_sig'] else Any)) |
| 111 | + |
| 112 | +def _inject_args(sig, types): |
| 113 | + """A function to inject arguments manually into a method signature before |
| 114 | + it's been parsed. If using keyword arguments use 'kw=type' instead in |
| 115 | + the types array. |
| 116 | + |
| 117 | + sig the string signature |
| 118 | + types a list of types to be inserted |
| 119 | + |
| 120 | + Returns the altered signature. |
| 121 | + """ |
| 122 | + if '(' in sig: |
| 123 | + parts = sig.split('(') |
| 124 | + sig = '%s(%s%s%s' % ( |
| 125 | + parts[0], ', '.join(types), |
| 126 | + (', ' if parts[1].index(')') > 0 else ''), parts[1] |
| 127 | + ) |
| 128 | + else: |
| 129 | + sig = '%s(%s)' % (sig, ', '.join(types)) |
| 130 | + return sig |
| 131 | + |
| 132 | +def _site_api(method=''): |
| 133 | + response_dict = default_site.dispatch(request, method) |
| 134 | + return jsonify(response_dict) |
| 135 | + |
| 136 | + |
| 137 | +class JSONRPC(object): |
| 138 | + |
| 139 | + def __init__(self, app=None, rule='/api', site=default_site): |
| 140 | + self.rule = rule |
| 141 | + self.site = site |
| 142 | + if app is not None: |
| 143 | + self.app = app |
| 144 | + self.init_app(self.app) |
| 145 | + else: |
| 146 | + self.app = None |
| 147 | + |
| 148 | + def init_app(self, app): |
| 149 | + app.add_url_rule(self.rule + '/<method>', '', _site_api, methods=['POST']) |
| 150 | + |
| 151 | + def method(self, name, authenticated=False, safe=False, validate=False, **options): |
| 152 | + def decorator(f): |
| 153 | + arg_names = getargspec(f)[0][1:] |
| 154 | + X = {'name': name, 'arg_names': arg_names} |
| 155 | + if authenticated: |
| 156 | + raise Exception('Not implement') |
| 157 | + else: |
| 158 | + _f = f |
| 159 | + method, arg_types, return_type = _parse_sig(X['name'], X['arg_names'], validate) |
| 160 | + _f.json_args = X['arg_names'] |
| 161 | + _f.json_arg_types = arg_types |
| 162 | + _f.json_return_type = return_type |
| 163 | + _f.json_method = method |
| 164 | + _f.json_safe = safe |
| 165 | + _f.json_sig = X['name'] |
| 166 | + _f.json_validate = validate |
| 167 | + self.site.register(method, _f) |
| 168 | + return _f |
| 169 | + return decorator |
0 commit comments