0

I have a function:

import json, requests

def pull(command, foo):
    headers = {'content-type': 'application/json'}
    payload = json.dumps({"method": command, "params": [foo], "jsonrpc": "2.0"})
    response = requests.get(serverURL, headers=headers, data=payload)

    return(response.json()['result'])

That I'm running in a loop (several million times) at the moment. I think that doing several batch calls would be much quicker that doing all these calls in series.

I can't seem to find any documentation on doing a batch RPC call in Python.

I've tried doing:

payload = json.dumps({"method": command, "params": [foo], "jsonrpc": "2.0"}, 
                     {"method": command, "params": [foo+1], "jsonrpc": "2.0"})

to no avail.

SLee
  • 101
  • 1
  • 4
  • 12
  • 2
    Surely that depends on the API you're calling, doesn't it? It's not up to Python to determine whether that server supports any particular batch functionality. – Daniel Roseman Jul 09 '15 at 07:53
  • I'm using an API that (supposedly?) allows batch calls. I wasn't sure if my code is correct or not. – SLee Jul 09 '15 at 08:05
  • 1
    I would think that that API should then tell you what to use to perform a batch call (e.g., what URL to access, or what arguments to use). Surely it can't be the same as you're using for a single request. –  Jul 09 '15 at 08:11

2 Answers2

0

The spec says you should pass an array of requests.

Your example has an error, you should pass a list or a tuple of RPC dicts to json.dumps, not multiple arguments:

See:

>>> json.dumps({"method": "do_thing", "params": [1], "jsonrpc": "2.0"},  {"method": "do_thing", "params": [1+1], "jsonrpc": "2.0"})
'{"jsonrpc": "2.0", "params": [1], "method": "do_thing"}'

Compared with:

>>> json.dumps([{"method": "do_thing", "params": [1], "jsonrpc": "2.0"},  {"method": "do_thing", "params": [1+1], "jsonrpc": "2.0"}])
'[{"jsonrpc": "2.0", "params": [1], "method": "do_thing"}, {"jsonrpc": "2.0", "params": [2], "method": "do_thing"}]'
MattH
  • 37,273
  • 11
  • 82
  • 84
0

Without much details of the API, I can't be sure what works, but here are a few things you can try:

payload = json.dumps([{"method": command, "params": [foo], "jsonrpc": "2.0"}, 
                      {"method": command, "params": [foo+1], "jsonrpc": "2.0"}])

or

payload = '\n'.join(json.dumps(x) for x in [
              {"method": command, "params": [foo], "jsonrpc": "2.0"}, 
              {"method": command, "params": [foo+1], "jsonrpc": "2.0"}
            ])
John
  • 1,856
  • 2
  • 22
  • 33