【问题标题】:Flask - receive and print jsonFlask - 接收并打印 json
【发布时间】:2021-05-31 14:01:53
【问题描述】:

我希望我的烧瓶服务器接受一个 json 文件并打印它。

我正在发送 json:

curl -X POST -F file=@/home/user1/Desktop/test.json 0.0.0.0:5000/testjson

这是服务器的代码:

@app.route('/testjson', methods=['POST'])
def trigger_json_test():
   POST_content = request.get_json()
   print(POST_content)
   return make_response(json.dumps({'fileid': "ok"}), 200)

虽然服务器以正确的响应进行响应,但我在终端看到的关于print() 的只是None

【问题讨论】:

    标签: json python-3.x flask


    【解决方案1】:

    request.get_json() 允许您获取在 http 请求正文中传递的 json(很明显,如果您已在标头中指定 application/json 作为请求的内容类型)。

    如果您将 json 作为文件发送,那么您可以通过 request 对象的 files 属性获取它:

    sent_files = request.files #request.files contains all file sent by the client
    

    【讨论】:

    • 谢谢。但是,当我执行print(sent_files) 时,这行得通,我得到ImmutableMultiDict([('file', <FileStorage: 'test.json' ('application/octet-stream')>)]) 。我是否必须对sent_files 进行任何后期处理,以便被识别为 json 或字典?
    • 是的,request.files 是一个字典,其中包含客户端发送到服务器的所有文件。要获得它,您需要这样做:json_file = sent_files['file']显然,如果您使用不同的名称发送它,请使用适当的名称而不是“文件”。要读取文件内容,请参阅此堆栈溢出问题:stackoverflow.com/questions/20015550/…
    • 我试过这个json_file = sent_files[test.json] 但我得到了`json_file = sent_files[test.json] NameError: name 'test' is not defined`。此外,这种方法意味着我必须对文件名进行硬编码。
    • 在你的情况下你可以通过json_file = sent_files['file']访问它,字典的参数是文件名,文件名不是你电脑上的文件名,而是你的名字当您使用 http 请求发送文件时将其提供给文件:curl -X POST -F file=@/home/user1/Desktop/test.json 0.0.0.0:5000/testjson,在您的情况下为 file =path。 test.json 给你这个错误,因为参数需要是一个字符串。我希望我很清楚,否则请要求其他澄清。
    • 非常感谢!打印json_file 给了我这个:<FileStorage: 'test.json' ('application/octet-stream')> 127.0.0.1 - - [31/May/2021 23:29:55] "POST /process HTTP/1.1" 200 -。我还有两个相关的问题 - 但为了让您获得更多积分,我将提出一个单独的问题而不是在这里提问(当然,如果您回答或不回答,这取决于您)。我将在评论中链接它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-26
    • 2018-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多