Search code examples
python-3.xpycurl

How to fix PyCurl command not uploading JSON file to server


I am trying to upload a JSON file to a server for use in testing. I have tried this code which gives the correct Status output but the file is not uploaded to the server:

import pycurl
import sys

mosaic_path = sys.argv[1]

file = open(mosaic_path)
print(mosaic_path)

c = pycurl.Curl()
c.setopt(c.URL, 'http://test-URL:21308/mosaic/testing/')
c.setopt(pycurl.HTTPHEADER, ['Content-Type: application/json', 'Accept: application/json'])
c.setopt(c.PUT, 1)
c.setopt(c.READDATA, file)
c.perform()
print('Status: %d' % c.getinfo(c.RESPONSE_CODE))
c.close()
file.close()

this cURL command does work:

curl -I -T 2by2_hero_2by2.json http://test-URL:21308/mosaic/testing

(I am trying to update these curl commands to python scripts)

any help would be greatly appreciated.


Solution

  • you may refer to this question: Uploading a file via pyCurl

    the way you did it would make http request header look like following:

    PUT /mosaic/testing/ HTTP/1.1
    Host: test-URL:21308
    Content-Type: application/json
    Accept: application/json
    
    <the content of mosaic_path>
    

    the server would not consider such headers to be a valid file transfer signal, because the only way to transfer file through http is by using Content-Type: multipart/form-data and reconstruct the way to send the file content(using boundry). refer to this question: How does HTTP file upload work?