2017-04-09 47 views
1

我有一个卷曲的POST elasticsearch做:卷曲张贴elasticsearch在python

curl -XPOST "http://localhost:9200/index/name" --data-binary "@file.json" 

我怎样才能做到这一点在Python的壳呢?基本上,因为我需要遍历许多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: coercing to Unicode: need string or buffer, list found 

回答

1

您可以使用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) 
+0

谢谢贴出我的代码往上顶。我收到了一个我无法弄清楚的TypeError。 – user6754289

+0

你需要遍历你的'send_post'函数,看看我的编辑。您收到的TypeError意味着您将数组指定为'requests.post'参数,它在期望字符串的位置 –

+0

明白了,我需要在检索文件的过程中解决一件事。感谢帮助! – user6754289

0

使用requests库。

import requests 
r = requests.post(url, data=data) 

它是那样简单。