我有一个curl POST要做的弹性搜索:
curl -XPOST "http://localhost:9200/index/name" --data-binary "@file.json"
如何在python shell中执行此操作?基本上是因为我需要遍历许多json文件。我希望能够在for循环中执行此操作。
import glob
import os
import requests
def index_data(path):
item = []
for filename in glob.glob(path):
item.append(filename[55:81]+'.json')
return item
def send_post(url, datafiles):
r = requests.post(url, data=file(datafiles,'rb').read())
data = r.text
return data
def main():
url = 'http://localhost:9200/index/name'
metpath = r'C:\pathtofiledirectory\*.json'
jsonfiles = index_data(metpath)
send_post(url, jsonfiles)
if __name__ == "__main__":
main()
我修复了这样做,但是给了我一个TypeError:
TypeError: coercing to Unicode: need string or buffer, list found
答案 0 :(得分:2)
您可以使用requests
http客户端:
import requests
files = ['file.json', 'file1.json', 'file2.json', 'file3.json', 'file4.json']
for item in files:
req = requests.post('http://localhost:9200/index/name',data=file(item,'rb').read())
print req.text
在编辑中,您需要:
for item in jsonfiles:
send_post(url, item)
答案 1 :(得分:0)