【问题标题】:How to read file sent from curl to Flask?如何读取从 curl 发送到 Flask 的文件?
【发布时间】:2016-07-20 01:50:23
【问题描述】:

烧瓶代码 -

 @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 参数是否错误(文件名)?或者我以错误的方式发送文件?

还有Upload a file to a python flask server using curl

试过了

   f = request.files['filename'] 

仍然,同样的错误。

【问题讨论】:

    标签: python curl flask


    【解决方案1】:

    您的curl 命令代码正在做的是读取文件hello.json 并将其放入请求的正文中。 (如果您需要将大量 JSON 发送到服务器,此功能实际上非常有用)。

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

    如果你想上传一个实际文件——比如上传一张图片——你需要多部分的表单编码,你告诉 curl 通过-F 参数发送。 (另请参阅:关于此的 SO 答案:https://stackoverflow.com/a/12667839/224334)。

    【讨论】:

    • 出现问题是因为我在 curl 中有 filename=@hello.json。 curl -H "Content-Type:application/json" -X POST 127.0.0.1:5000/messages --data @hello.json 和 request.get_json 似乎解决了这个问题。非常感谢!
    猜你喜欢
    • 2021-12-27
    • 1970-01-01
    • 2012-08-15
    • 1970-01-01
    • 2020-02-19
    • 2020-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多