You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

部署在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 Request

The 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发布管道配置

Azure DevOps发布管道配置截图

App Service访问限制设置

App Service访问限制设置截图

可能的原因及解决办法

  • Flask启动逻辑问题:本地启动依赖if __name__ == '__main__':分支,但Azure App Service生产环境不会触发该逻辑。解决方式:

    1. 将app.py重命名为application.py(App Service默认识别该文件名)
    2. 在项目根目录添加requirements.txt,加入gunicorn,然后创建startup.txt写入gunicorn app:app
    3. 登录Azure门户,进入App Service的“配置”-“常规设置”,设置启动命令为gunicorn app:app或python app.py
  • 请求与路由验证:

    1. 确认send_request.py中的<app>替换为实际的App Service名称,URL无误
    2. 先测试GET请求访问http://<app>.azurewebsites.net/chat,若返回null说明路由可达,问题出在JSON解析;若仍400则路由未正确映射
    3. 在chat函数中添加日志排查数据接收情况:
      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的“日志流”,确认是否接收到正确的JSON数据
  • 环境一致性检查:

    1. 确认App Service的Python版本与本地开发环境一致(在Azure门户“配置”-“常规设置”中查看)
    2. 通过Kudu控制台查看site/wwwroot目录,确认部署包完整、依赖已正确安装

内容的提问来源于stack exchange,提问作者Atinesh Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 15:10:17