将此curl命令转换为python请求库

时间:2018-04-24 14:45:34

标签: python python-3.x python-2.7 curl python-requests

我正在编写一个脚本来将file.csv转换为.json,并在Windows上将其用于将脚本转换为.exe文件。 这是脚本:

 import csv
import json
import requests


origen=raw_input('Inserta la ruta del fichero origen: ')

destino=raw_input('Inserta la ruta del fichero a generar: ')

indice=raw_input('Inserta nombre del indice: ')

ip=raw_input('Inserta la ip del servidor: ')


jsonfile = open(destino, 'w')



with open(origen,'r') as infile:
    lineas = infile.readlines()
fieldnames=[]

tienecab=raw_input('Tiene cabecera? s/n: ')
k=0


if(tienecab == 's'):
    for linea in lineas:
        for i in linea:
                if (k==0):
                    fieldnames=lineas
                    k=1
    reader = csv.DictReader(fieldnames)
    rowid = 0

    for row in reader:
        jsonfile.write('{"index":{"_index":"' + indice  + '","_id":' + str(rowid) + '}}\n')
        json.dump(row, jsonfile)
        jsonfile.write('\n')
        rowid += 1

elif(tienecab == 'n'):
    numcab=raw_input('Cuantas columnas tiene la cabecera: ')
    var=int(numcab)
    p=1
    while p<=var:
        apendice=raw_input('Escribe el valor de la columna ' + str(p) + ': ')
        fieldnames.append(apendice)
        p+=1


        reader = csv.DictReader(lineas,fieldnames)
        rowid = 0

        for row in reader:
            jsonfile.write('{"index":{"_index":"' + indice  + '","_id":' + str(rowid) + '}}\n')
            json.dump(row, jsonfile)
            jsonfile.write('\n')
            rowid += 1



jsonfile.close()


url = r'192.168.1.149:9200/arenero/doc/_bulk?pretty'
headers = {'Content-Type': 'application/x-ndjson'}
files = {'file': open(destino, 'rb')}
r = requests.post(url, headers=headers, files=files)

我需要修改脚本的结尾以执行与此curl命令相同的操作

卷曲-H&#39;内容类型:application / x-ndjson&#39; -XPOST&#39; 192.168.1.142:9200 / index / doc / _bulk?pretty&#39; --data-binary @ file.json

(已安装请求python库)

1 个答案:

答案 0 :(得分:1)

尝试这样的事情:

import requests
url = r'192.168.1.142:9200/index/doc/_bulk?pretty'
headers = {'Content-Type': 'application/x-ndjson'}
files = {'file': open('PATH_TO_FILE.json', 'rb')}
r = requests.post(url, headers=headers, files=files)