Azure部署的FastAPI应用Post请求报Method Not Allowed求助
排查FastAPI部署到Azure后Post请求返回405 Method Not Allowed的问题
以下是几个常见的排查方向和解决方法:
1. 验证端点URL的准确性
- 确认请求URL完全匹配FastAPI的路由定义:
- 检查
endpoint变量是否包含完整协议(http://或https://)以及正确的Azure App Service域名(例如https://yourappname.azurewebsites.net)。 - 检查URL拼接后是否存在多余斜线:比如路由定义为
/pdf-upload/{market}/{data_providers},若请求URL末尾多了/,在严格斜线模式下会匹配失败。 - 确保最终URL格式为
https://yourappname.azurewebsites.net/pdf-upload/market_value/data_providers_value
- 检查
2. 对路径参数进行URL编码
如果market或data_providers包含特殊字符(空格、&、/等),直接拼接会导致FastAPI无法解析正确路由,返回405。需对路径参数做URL编码:
import requests from urllib.parse import quote market = "market with space" data_providers = "data&providers" # 对参数进行URL编码 market_encoded = quote(market) data_providers_encoded = quote(data_providers) filepath = r"filepath" file = {'file': open(filepath, 'rb')} url = f"https://yourappname.azurewebsites.net/pdf-upload/{market_encoded}/{data_providers_encoded}" response = requests.post(url=url, files=file)
3. 检查Azure的重定向配置
- 若Azure App Service启用了HTTP到HTTPS的强制重定向,用HTTP发送POST请求会被重定向为GET请求,触发405错误。确保请求URL使用
https://协议。 - 可在App Service的「配置」->「常规设置」中查看「HTTPS强制」选项,确认是否开启,开启状态下必须使用HTTPS请求。
4. 验证FastAPI的路由匹配模式
FastAPI默认采用宽松斜线匹配(带斜线和不带斜线的路径视为同一路由),但如果手动设置了strict_slash=True,则会严格区分:
# 检查是否存在此类配置 app = FastAPI(strict_slash=True)
若开启严格模式,需确保请求URL路径结尾无多余斜线,与路由定义完全一致。
5. 检查Azure的URL重写规则
如果在Azure App Service的「配置」->「路径映射」中设置了URL重写规则,可能会修改请求路径,导致无法匹配FastAPI路由。可暂时禁用重写规则测试是否恢复正常。
内容的提问来源于stack exchange,提问作者Elliott Davey
相关产品推荐
相关产品推荐

