从urllib和Postman调用时,Flask服务器接收到的POST请求数据中的差异

时间:2018-11-30 13:34:38

标签: python flask httprequest postman urllib

flask服务器仅打印从发出POST请求的客户端接收到的数据。它还会检查 Authorization 标头的状态

from flask import Flask, request

app = Flask(__name__)

@app.route('/random', methods=['POST'])
def random():
    if request.method == 'POST':
        if request.headers.get('Authorization') and request.headers.get('Content-Type') == 'application/json':
            print(request.get_json())
            print(request.data)
            return "Success"
        else:
            print(request.get_json())
            print(request.data)
            return "Bad request"

app.run(host='0.0.0.0', port=5000, debug=True)

现在,当我从 Postman 测试API时,它可以完美运行。但是,我们将对其进行稍微不同的测试。在您的标头中取消选中 Authorization Content-Type 标头,然后在正文中发送此json-

{"spam": 1, "eggs": 2, "bacon": 0}

终端上的输出是-

None
b'{"spam": 1, "eggs": 2, "bacon": 0}'
127.0.0.1 - - [30/Nov/2018 12:25:33] "?[37mPOST /random HTTP/1.1?[0m" 200 -

现在,我们将通过urllib执行相同的操作。以下是该代码-

import json
import urllib.request
import urllib.parse
d = {"spam": 1, "eggs": 2, "bacon": 0}
data = json.dumps(d)
data = data.encode()
req = urllib.request.Request("http://localhost:5000/random", data)
req.add_header('Content-Type', 'application/json')
req.add_header('Authorization', 12345)

with urllib.request.urlopen(req) as f:
    print(f.read().decode('utf-8'))

哪个效果很好。但是,为了重新创建我们对Postman所做的操作,我们将对req.add_header行进行注释,如下所示-

#req.add_header('Content-Type', 'application/json')
#req.add_header('Authorization', 12345)

然后,当我们执行脚本时,我们会从中获得输出-

None
b''
127.0.0.1 - - [30/Nov/2018 12:27:18] "?[37mPOST /random HTTP/1.1?[0m" 200 -

我需要知道两者中哪一个是正确的预期行为,为什么这两个是不同的?

0 个答案:

没有答案