jsonrpc-base

Pure python standard library JSONRPC data interface
git clone git://git.defalsify.org/python-jsonrpc-base.git
Info | Log | Files | Refs | LICENSE

parse.py (1562B)


      1 # standard imports
      2 import json
      3 
      4 # local imports
      5 from .base import JSONRPCBase
      6 from .error import (
      7         JSONRPCParseError,
      8         JSONRPCInvalidRequestError,
      9         )
     10 from .interface import (
     11         jsonrpc_request,
     12         )
     13 
     14 
     15 def jsonrpc_validate_dict(o):
     16     version = o.get('jsonrpc')
     17     if version == None:
     18         raise JSONRPCParseError('missing jsonrpc version field')
     19     elif version != JSONRPCBase.version_string:
     20         raise JSONRPCInvalidRequestError('Invalid version {}'.format(version))
     21 
     22     method = o.get('method')
     23     if method == None:
     24         raise JSONRPCParseError('missing method field')
     25     elif type(method).__name__ != 'str':
     26         raise JSONRPCInvalidRequestError('method must be str')
     27 
     28     params = o.get('params')
     29     if params == None:
     30         raise JSONRPCParseError('missing params field')
     31     elif type(params).__name__ != 'list':
     32         raise JSONRPCParseError('params field must be array')
     33 
     34     request_id = o.get('id')
     35     if request_id == None:
     36         raise JSONRPCParseError('missing id field')
     37     if type(request_id).__name__ not in ['str', 'int']:
     38         raise JSONRPCInvalidRequestError('invalid id value, must be string or integer')
     39 
     40     return o 
     41 
     42 
     43 def jsonrpc_from_str(s):
     44     o = json.loads(s)
     45     return jsonrpc_from_dict(o)
     46 
     47 
     48 def jsonrpc_from_dict(o):
     49     o_parsed = jsonrpc_validate_dict(o)
     50     req = jsonrpc_request(o_parsed['method'], request_id=o_parsed['id'])
     51     req['params'] = o_parsed['params']
     52     return req
     53 
     54 
     55 def jsonrpc_from_file(f):
     56     o = json.load(f)
     57     return jsonrpc_from_dict(o)