部署在Azure App Service的Flask应用报405 Method Not Allowed错误求助
问题
本地测试正常的Flask Blueprint模块化应用,部署到Azure App Service后,通过Postman或Python脚本发送POST请求时出现405 Method Not Allowed错误,错误内容如下:
<!doctype html> <html lang=en> <title>405 Method Not Allowed</title> <h1>Method Not Allowed</h1> <p>The method is not allowed for the requested URL.</p>
应用结构:
/root |- app.py |- routes | |- test.py |- send_request.py |- requirements.txt
test.py
from flask import Blueprint, request, jsonify route = Blueprint("test", __name__, url_prefix="/test") @route.route("/", methods=["POST"]) def test(): data = request.json["test"] print(data) return jsonify(data)
app.py
from flask import Flask from routes import test app = Flask(__name__) app.register_blueprint(test.route) if __name__ == "__main__": app.run(debug=True)
send_request.py
import requests import json url = "https://<app>.azurewebsites.net/test" payload = json.dumps({ "test": "Hello World!" }) headers = { 'Content-Type': 'application/json' } response = requests.request("POST", url, headers=headers, data=payload) print(response.text)
解决方案
按以下步骤排查并修复:
1. 设置正确的启动命令
Azure App Service默认不会自动识别Flask应用的启动入口,需手动配置:
- 进入Azure Portal的目标App Service资源,打开「配置」>「常规设置」
- 在「启动命令」中填入:
gunicorn --bind=0.0.0.0 --timeout 600 app:app
(若你的Flask实例名称不是app,需对应修改;gunicorn需添加到requirements.txt中)
2. 补全依赖文件
确保requirements.txt包含运行所需的核心依赖:
Flask>=2.0.0 gunicorn>=20.0.0
Azure部署时会自动安装这些依赖,缺少gunicorn可能导致应用运行异常。
3. 处理URL尾部斜杠问题
Azure App Service可能会对URL做自动重定向,导致请求方法被改变:
- 尝试将请求URL改为
https://<app>.azurewebsites.net/test/(添加尾部斜杠) - 或者修改Flask路由,允许带/和不带/的请求:
@route.route("/", methods=["POST"], strict_slashes=False)
4. 检查HTTP版本设置
在「配置」>「常规设置」中,将「HTTP版本」设置为2.0,避免协议兼容问题。
5. 查看应用运行日志
若以上步骤无效,打开Azure Portal的「日志流」查看应用启动日志,确认Flask应用是否正常启动、路由是否正确注册,排查潜在运行报错。
内容的提问来源于stack exchange,提问作者Atinesh Singh
相关产品推荐
相关产品推荐

