how to post data and binary data using urllib2 in python

how to post data and binary data using urllib2 in python

I essentially want to do this:
curl -X POST “http://URL?u=user&p=password” –data-binary @myconfig.json

with urllib2.
I found examples for sending just the user and password, or just the binary, but not both at the same time, and some contradict each other.
I am doing this to create an influxdb with a retention policy based on instructions here:
https://docs.influxdata.com/influxdb/v0.8/advanced_topics/sharding_and_storage/
curl -X POST “http://localhost:8086/cluster/database_configs/mydb?u=root&p=root” –data-binary @myconfig.json

Thanks!

Solutions/Answers:

Solution 1:

import urllib2
import json

url = 'http://url.com?u=user&p=pass'
data = json.dumps({'config':'configData'}) # your JSON File goes in here, as argument to dumps.
cont_len = len(data)
req = urllib2.Request(url, data, {'Content-Type': 'application/json', 'Content-Length': cont_len})
f = urllib2.urlopen(req)
response = f.read()
f.close()

That solves it!

Note that, with urllib2, you cannot specify the .json file. You simply put its content into the json.dumps function.

References

Related:  InfluxDB - Getting only last value in query