繁体   English   中英

uWSGI 400 错误请求

[英]uWSGI 400 Bad Request

我正在尝试通过 uWSGI/nginx 为 python 应用程序提供服务。 Ubuntu 21.10 uWSGI 2.0.20

该应用程序有几个端点:

  1. 用于测试的 GET(它只返回字符串“hello”)
  2. 具有不同路由的 POST 端点,它接受一些 json 数据并返回一些 output。

该应用程序在托管环境中运行。

  • 当我尝试将它放在 nginx 服务器后面时,GET 端点工作正常,但 POST 重新调整为 400
  • 然后我尝试仅通过 flask(无 uWSGI/nginx)运行应用程序,两个端点都有效。
  • 然后我关闭 flask 进程并通过命令行运行 uWSGI:

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不会导致端口冲突)

所以:

  • 应用程序不是问题。 否则 flask 也会崩溃
  • Nginx 配置似乎没有问题; GET 端点正常工作

我该如何调试这个问题?

重复你的错误

由于您没有发布有关您的 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

  • 第二种解决方案:更改 web 应用程序解析数据的方式。 如果您发送格式为 json 的数据,那么您可以在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM