2

I have a curl POST to do for elasticsearch:

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

How can I do this in a python shell? Basically because i need to loop over many json files. I want to be able to do this in a for loop.

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

I fixed to do this, but is giving me a TypeError:

TypeError: coercing to Unicode: need string or buffer, list found

2 Answers 2

3

You can use requests http client :

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

From your edit, you would need :

for item in jsonfiles:
    send_post(url, item)
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks posted my code up top. Am receiving a TypeError that I can't figure out.
You need to loop through your send_post function see my edit. The TypeError you receive means that you specify array as requests.post arguments where it expects string
Got it, I needed to fix one more thing in how I was retrieving the file. Thanks for help!
0

Use the requests library.

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

It is as simple as that.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.