Example #1
0
def invokeAPI(name, data, where=None, port=8000):
    "make a vesper api call"
    url = "http://localhost:%d/api/%s" % (port, name)

    if isinstance(data, dict):
        data = json.dumps(data)

    post = {"data": data}
    if where:
        post["where"] = where

    tmp = urlopen(url, data=urlencode(post)).read()
    return json.loads(tmp)
Example #2
0
 def handleTestresult(kw, retval):
     queue.put(json.loads(kw._postContent))
     kw._responseHeaders['Content-Type'] = 'application/json'
     return '"OK"'
Example #3
0
def datarequest(kw, retval):
    '''
    Accepts a JSON-RPC 2.0 (see http://groups.google.com/group/json-rpc/web/json-rpc-2-0)
    request (including a batch request).
    '''
    from vesper import pjson

    newresourcesCreated = {}
    
    def handleRequest(id=None, method=0, params=0, jsonrpc=None):
        requestid = id; action = method; data = params
        response = dict(id=requestid, jsonrpc='2.0')
        if requestid is None or jsonrpc != '2.0':
            response['error'] = dict(code=-32600, message='Invalid Request')
            return response
        
        #don't catch exceptions for write operations because we want 
        #the whole request transaction to be aborted
        #sendJsonRpcError below it will turn the error into json-rpc error response
        if action == 'update':
            addStmts, removeStmts = dataStore.update(data)
            #XXX better return values
            result = dict(added=pjson.tojson(addStmts), removed=pjson.tojson(removeStmts))
        elif action == 'replace':
            addStmts, removeStmts = dataStore.replace(data)
            #XXX better return values
            result = dict(added=pjson.tojson(addStmts), removed=pjson.tojson(removeStmts))
        elif action == 'add':
            addJson = dataStore.add(data)
            result = dict(added=addJson)
        elif action == 'create':
            addJson, newresources = dataStore.create(data)
            if newresources:
                newresourcesCreated['new'+str(id)] = newresources[0]
            result = dict(added=addJson, new=newresources)
        elif action == 'query':
            #returns { errors, results }
            if isinstance(data, (str, unicode)):
                result = dataStore.query(data, captureErrors=True) 
            else:
                data['captureErrors'] = True
                result = dataStore.query(**data)
            if result.errors:
                response['error'] = dict(code=0, message='query failed', 
                                                    data = result.errors)
                return response
        elif action == 'remove':
            removeJson = dataStore.remove(data)
            result = dict(removed=removeJson)
        elif action == 'transaction_info':
            comment = params.get('comment')
            result = {}
            if comment:
                comment = Template(comment).safe_substitute(newresourcesCreated)
                result['comment'] = comment
                kw['__transaction_comment'] = comment
        else:
            response['error'] = dict(code=-32601, message='Method not found')
            return response
        
        response['result'] = result
        return response
    
    if kw.urlvars.store:
        dataStore = kw.__server__.stores.get(kw.urlvars.store)
    else:
        dataStore = kw.__server__.defaultStore

    if not dataStore:
        response = dict(id=None, jsonrpc='2.0', error=dict(code=-32600, 
            message='Invalid Request: store "%s" not found' % kw.urlvars.store))
    else:                                             
        postdata = kw._postContent
        # some json libs return unicode keys, which causes problems with **dict usages
        try:
            requests = json.loads(postdata, object_hook=lambda x: 
                                dict([(str(k),v) for (k,v) in x.items()]))
        except:
            response = dict(id=None, jsonrpc='2.0', error=dict(code=-32700, 
                                                      message='Parse error'))
        else:
            if not isinstance(requests, list):
               requests = [requests] 
            #XXX vesper.app should set a default content-type 
            kw._responseHeaders['Content-Type'] = 'application/json'
            response = [isinstance(x, dict) and handleRequest(**x) or 
                dict(id=hasattr(x, 'get') and x.get('id') or None, jsonrpc='2.0',
                            error=dict(code=-32600, message='Invalid Request'))
                                                                for x in requests]
            log.debug('request: \n  %r\n response:\n   %r', requests, response)
    return json.dumps(response, indent=4)