部署在Azure App Service的Flask应用触发400 Bad Request错误求助
Flask应用部署到Azure App Service后POST请求返回400 Bad Request问题
我通过Azure DevOps构建与发布管道将一个简单的Flask应用部署到Azure App Service。该应用仅接收用户输入并返回结果,本地部署及测试均运行正常,可得到预期输出,但部署到App Service后,通过Postman或Python发送请求时出现以下错误:
<!doctype html>
400 Bad Request Bad RequestThe browser (or proxy) sent a request that this server could not understand.
相关代码与配置
app.py
from flask import Flask, request, jsonify app = Flask(__name__) @app.route('/chat', methods=['GET', 'POST']) def chat(): data = request.json return jsonify(data) if __name__ == '__main__': app.run(debug=True)
send_request.py
import requests import json url = "http://<app>.azurewebsites.net/chat" payload = json.dumps({ "name": "Atinesh Singh" }) headers = { 'Content-Type': 'application/json' } response = requests.request("POST", url, headers=headers, data=payload) print(response.text)
Azure DevOps发布管道配置

App Service访问限制设置

可能的原因及解决办法
Flask启动逻辑问题:本地启动依赖
if __name__ == '__main__':分支,但Azure App Service生产环境不会触发该逻辑。解决方式:- 将
app.py重命名为application.py(App Service默认识别该文件名) - 在项目根目录添加
requirements.txt,加入gunicorn,然后创建startup.txt写入gunicorn app:app - 登录Azure门户,进入App Service的“配置”-“常规设置”,设置启动命令为
gunicorn app:app或python app.py
- 将
请求与路由验证:
- 确认
send_request.py中的<app>替换为实际的App Service名称,URL无误 - 先测试GET请求访问
http://<app>.azurewebsites.net/chat,若返回null说明路由可达,问题出在JSON解析;若仍400则路由未正确映射 - 在
chat函数中添加日志排查数据接收情况:
查看App Service的“日志流”,确认是否接收到正确的JSON数据import logging logging.basicConfig(level=logging.INFO) @app.route('/chat', methods=['GET', 'POST']) def chat(): logging.info(f"Headers: {request.headers}") logging.info(f"Raw data: {request.data}") data = request.json return jsonify(data)
- 确认
环境一致性检查:
- 确认App Service的Python版本与本地开发环境一致(在Azure门户“配置”-“常规设置”中查看)
- 通过Kudu控制台查看
site/wwwroot目录,确认部署包完整、依赖已正确安装
内容的提问来源于stack exchange,提问作者Atinesh Singh
相关产品推荐
相关产品推荐

