0

I am programming a script to convert a file.csv into .json, and using it on windows converting the script into a .exe file. This is the script:

 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)

I need to modify the end of the script to do the same as this curl command

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

(Requests python library is installed)

GRojo
  • 1
  • 1

1 Answers1

1

Try something like this:

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)
Nishant Nawarkhede
  • 8,234
  • 12
  • 59
  • 81
Ivan Vinogradov
  • 4,269
  • 6
  • 29
  • 39