如何阅读从卷曲发送到Flask的文件? [英] How to read file sent from curl to Flask?

查看:197
本文介绍了如何阅读从卷曲发送到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错误(文件名)?或者我以错误的方式发送文件?

另外上传一个文件到一个python烧瓶服务器使用curl



尝试做

 f = request.files ['filename'] 

同样的错误。 hello.json 并将其放在请求的正文中。 (这个特性实际上非常有用,如果你有大量的JSON需要发送到服务器)。

通常在 application / json 请求你发送JSON作为请求的主体,所以这个可以是你想要的。您可以使用 request.get_json 将此数据作为一个Python字典。

如果你想上传一个真实的文件 - 就像上传一张图片一样 - 你需要多部分形式的编码, curl通过 -F 参数发送。 (另请参见:关于此问题的答案: https://stackoverflow.com/a/12667839/224334 )。


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 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>

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.

解决方案

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 ).

这篇关于如何阅读从卷曲发送到Flask的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆