[英]uWSGI 400 Bad Request
我正在尝试通过 uWSGI/nginx 为 python 应用程序提供服务。 Ubuntu 21.10
uWSGI 2.0.20
该应用程序有几个端点:
该应用程序在托管环境中运行。
uwsgi --socket 0.0.0.0:5555 --protocol=http -w runserver:app
在这种情况下,GET 可以正常工作,
[pid: 19308|app: 0|req: 5/5] 103.113.137.67 () {36 vars in 705 bytes} [Tue Nov 23 08:21:12 2021] GET / => generated 5 bytes in 0 msecs (HTTP/1.1 200) 2 headers in 78 bytes (1 switches on core 0)
但 POST 失败
[pid: 19308|app: 0|req: 2/2] 103.113.137.67 () {26 vars in 394 bytes} [Tue Nov 23 07:52:40 2021] POST /distance/term => generated 187 bytes in 1 msecs (HTTP/1.1 400) 2 headers in 89 bytes (1 switches on core 0)
(nginx作为反向代理被配置为监听55555端口,所以5555上的uWSGI不会导致端口冲突)
所以:
我该如何调试这个问题?
重复你的错误
由于您没有发布有关您的 POST 端点以及您如何访问您的应用程序的代码。 所以我假设你的代码如下:
# runserver.py
from flask import Flask
from flask import request
app = Flask(__name__)
@app.route('/post',methods=['POST'])
def post():
data=request.form['data']
return data
@app.route('/get',methods=['GET'])
def get():
return "hello"
然后像你一样启动 uwsgi
uwsgi --socket 0.0.0.0:5555 --protocol=http -w runserver:app
假设您正在通过 bash 访问您的应用程序
curl -X POST http://localhost:5555/post -d '{"data": "someData"}' -H 'Content-Type: application/json'
然后您可以在 bash 中看到以下内容,表示 400 错误请求错误。
<!doctype html>
<html lang=en>
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>The browser (or proxy) sent a request that this server could not understand.</p>
同时,如果您通过curl http://localhost:5555/get
访问 GET 端点,则可以正确收到“hello”。
原因:
如果你真的在做上面的事情,那么原因是你发送的数据类型和 web app 想要解析的数据类型不匹配。 request.form
用于读取格式为key1=value1&key2=value2
及以上的数据 request 发送格式为{key:value}
的数据
解决方案:
如果你真的在做上述事情,那么你有两个解决方案:
curl -X POST http://localhost:5555/post -d "data=someData" -H 'Content-Type:application/x-www-form-urlencoded'
,它发送格式为key=value
的数据, request.form
可以正确解析它。 您可以在 bash 中看到结果someData
。
runserver.py
中将request.form
替换为request.json
,例如@app.route('/post',methods=['POST'])
def post():
data=request.json['data']
return data
然后访问您的应用
curl -X POST http://localhost:5555/post -d '{"data": "someData"}' -H 'Content-Type: application/json'
,您将在 bash 中看到结果someData
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.