Python 如何读取从curl发送到Flask的文件?
烧瓶代码-Python 如何读取从curl发送到Flask的文件?,python,curl,flask,Python,Curl,Flask,烧瓶代码- @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 =
@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)
运行时,我得到的错误为-
curl -H "Content-Type:application/json" -X POST http://127.0.0.1:5000/messages --data filename=@hello.json
<!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>
然而,同样的错误 您的
curl
命令代码所做的是读取文件hello.json
,并将其放入请求主体中。(如果您需要向服务器发送大量JSON,那么此功能实际上非常有用)
通常,在application/json
请求中,您将json作为请求的主体发送,因此这可能是您想要的。您可以使用以Python字典的形式获取此数据
如果您想要上传一个实际的文件,就像上传一张图片一样,您需要多部分表单编码,您可以告诉curl通过
-F
参数发送。(另请参见:关于这个问题的答案:)。问题出现了,因为我在curl中有filename=@hello.json。curl-H“Content Type:application/json”-X POST--data@hello.json和request.get_json似乎解决了这个问题。非常感谢你!
f = request.files['filename']