Convert solr curl updateJSON syntax to python using urllib2
I would try
import urllib2with open('books.json', 'rb') as data_file: my_data = data_file.read()req = urllib2.Request(url='http://localhost:8983/solr/update/json?commit=true', data=my_data)req.add_header('Content-type', 'application/json')f = urllib2.urlopen(req)# Begin using data like the followingprint f.read()
From this you can see that the --data-binary parameter is just data sent to the server like in a POST
request. When that parameter begins with the @ sign, it means to read data from a file. In this case, it's the file 'books.json'. You also need to send the header (the -H
parameter of curl
). So you only need to call the add_header
method with the header name and its value.
Hope that gets you started. More info about urllib2 can be found at http://docs.python.org/2/library/urllib2.html
Because urllib2 is not available in Python 3.x I offer this alternative.This code snippet worked for me using Python 3.3 and the excellent requests library
import requests def postXml(host, xmlFile): url = "http://%s:8983/solr/update" % host headers = {"content-type" : "text/xml" } params = {"commit" : "false" } payload = open(xmlFile, "rb").read() r = requests.post(url, data=payload, params=params, headers=headers) print("got back: %s" % r.text)