Reputation: 43
Flask code -
@app.route('/messages', methods = ['POST'])
def api_message():
if request.headers['Content-Type'] == 'text/plain':
return "Text Message: " + request.data
elif request.headers['Content-Type'] == 'application/json':
f = open(filename,'r')
l = f.readlines()
f.close()
return len(l)
On running, I get error as -
curl -H "Content-Type:application/json" -X POST http://127.0.0.1:5000/messages --data [email protected]
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<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.
Upvotes: 1
Views: 2497
Reputation: 13972
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: https://stackoverflow.com/a/12667839/224334 ).
Upvotes: 2