将solr curl updateJSON语法转换为使用urllib2的python代码

2 投票
2 回答
3467 浏览
提问于 2025-04-17 19:23

我一直在学习Solr4.0,现在在看他们的文档,里面有关于如何更新JSON文档的内容,示例看起来是这样的:

cd example/exampledocs
curl 'http://localhost:8983/solr/update/json?commit=true' --data-binary @books.json -H 'Content-type:application/json'

这个方法运行得很好,我可以在我的solr索引中看到更新后的文档。不过,我在想如何在Python中通过urllib2使用这个curl命令。也就是说,类似于:

theurl=r"""http://localhost:8983/solr/update/json?commit=true --data-binary @books.json -H 'Content-type:application/json'"""
import urllib2
import httplib
import cookielib
...use urllib2 to post theurl

但是,这样做不行。看起来urllib2不识别上面构造的theurl(比如-H这个选项显然是curl特有的)。那么,应该如何格式化theurl,才能让它在urllib2中使用呢?

2 个回答

0

因为在Python 3.x中没有urllib2这个模块,所以我提供了一个替代方案。这个代码片段在我使用Python 3.3和很棒的requests库时是有效的。

 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)
5

我会尝试这样做

import urllib2
with 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 following
print f.read()

从这里你可以看到,--data-binary这个参数就像在发送一个POST请求时发送的数据。这个参数如果以@符号开头,意味着要从一个文件中读取数据。在这个例子中,就是文件'books.json'。你还需要发送一个头信息(也就是curl-H参数)。所以你只需要调用add_header方法,并提供头信息的名称和它的值。

希望这能帮到你。关于urllib2的更多信息,可以在这里找到:http://docs.python.org/2/library/urllib2.html

撰写回答