【问题标题】:Transform this curl command to python requests library [duplicate]将此 curl 命令转换为 python 请求库 [重复]
【发布时间】:2018-04-24 14:45:34
【问题描述】:

我正在编写一个脚本来将 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 命令做同样的事情

curl -H 'Content-Type: application/x-ndjson' -XPOST '192.168.1.142:9200/index/doc/_bulk?pretty' --data-binary @file.json

(请求安装python库)

【问题讨论】:

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


    【解决方案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)
    

    【讨论】:

    • 我把原来的问题改了,方便大家查找错误
    猜你喜欢
    • 2018-10-21
    • 2021-07-08
    • 2018-09-27
    • 2020-08-15
    • 2017-07-12
    • 1970-01-01
    • 2016-11-25
    • 1970-01-01
    • 2016-05-20
    相关资源
    最近更新 更多