Search code examples
pythonarraysjsonposturllib2

Python POST sql query result


I want to send a bunch of results to a server.

cur.execute('SELECT a,b,c,b FROM wicap WHERE a.num > 600 limit 25')
r = cur.fetchall()

r at this time is:

[(1487590224, 1487614532, -75, -41, 504, -73),
(1487596562, 1487614915, -75, -59, 156, -75),...]

I want to do something like:

response = urllib2.urlopen('http://example.com/post/', data=r)

And on the server side be able to get the data via:

def POST()
data = web.data()
for record in data...

and then process the query result in the server.

urlencode fails with ValueError: too many values to unpack I've tried creating a json with res = [dict((cur.description[i][0], value) for i, value in enumerate(row)) for row in r] but f = urllib2.urlopen(_url,res) returns TypeError: must be string or buffer, not list

Ideas are welcome!


Solution

  • You need to encode the data to json with json.dumps:

    import json
    
    
    r = [(1487590224, 1487614532, -75, -41, 504, -73), (1487596562, 1487614915, -75, -59, 156, -75)]
    response = urllib2.urlopen('http://example.com/post/', data=json.dumps(r))