Kinara Shah Kinara Shah - 1 year ago 207
Python Question

How to read file sent from curl to Flask?

Flask code -

@app.route('/messages', methods = ['POST'])
def api_message():

if request.headers['Content-Type'] == 'text/plain':
return "Text Message: " +

elif request.headers['Content-Type'] == 'application/json':
f = open(filename,'r')
l = f.readlines()
return len(l)

On running, I get error as -

curl -H "Content-Type:application/json" -X POST --data filename=@hello.json

<title>500 Internal Server Error</title>
<h1>Internal Server Error</h1>
<p>The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.</p>

Am I accessing the curl param wrong (filename)? Or I am sending the file in wrong way?

Also Upload a file to a python flask server using curl

Tried doing

f = request.files['filename']

Still, same error.

Answer Source

What your curl command code is doing is reading the file hello.json and putting it in the body of the request. (This feature is actually very useful if you have a large chunk of JSON you need to send to the server).

Normally in application/json requests you send the JSON as the body of the request, so this may be what you want. You can use request.get_json to get this data as a Python dictionary.

If you want to upload an actual file - like uploading a picture - you want multi part form encoding, which you tell curl to send via the -F parameter. (See also: an SO answer about this: ).