如何阅读从卷曲发送到Flask的文件? [英] How to read file sent from curl to Flask?
问题描述
@ app.route('/ messages',methods = ['POST'])
def api_message():
$ b $如果request.headers ['Content-Type'] =='text / plain':
returnText Message:+ request.data
elif request.headers ['Content-Type'] =='application / json':
f = open(filename,'r')
l = f.readlines()
f.close()
return len(l)
运行时,错误为 -
curl -HContent-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内部伺服器错误< / title>
< h1>内部伺服器错误< / h1>
< p>服务器遇到内部错误,无法完成您的请求。服务器过载或应用程序出现错误。< / p>
我是否访问curl param错误(文件名)?或者我以错误的方式发送文件?
尝试做
f = request.files ['filename']
同样的错误。 hello.json 并将其放在请求的正文中。 (这个特性实际上非常有用,如果你有大量的JSON需要发送到服务器)。
通常在 如果你想上传一个真实的文件 - 就像上传一张图片一样 - 你需要多部分形式的编码, curl通过 Flask code - On running, I get error as - 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 Still, same error. What your Normally in 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 这篇关于如何阅读从卷曲发送到Flask的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! application / json
请求你发送JSON作为请求的主体,所以这个可以是你想要的。您可以使用 request.get_json 将此数据作为一个Python字典。
-F
参数发送。 (另请参见:关于此问题的答案: https://stackoverflow.com/a/12667839/224334 )。 @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>
f = request.files['filename']
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).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.-F
parameter. (See also: an SO answer about this: https://stackoverflow.com/a/12667839/224334 ).