FastAPI打包为wheel包后API接口报405 Method Not Allowed问题求助
我正在开发基于Angular UI的FastAPI项目,打包为wheel包前运行一切正常。使用命令:
python3.9 setup.py bdist_wheel
生成wheel包后,安装运行时UI服务器可成功启动在http://127.0.0.1:8000/,但调用POST接口/api/devices/connect时抛出错误:
INFO: 127.0.0.1:54394 - "POST /api/devices/connect HTTP/1.1" 405 Method Not Allowed
同时访问http://127.0.0.1:8000/docs也会返回相同的405错误。
项目main.py代码如下:
app = FastAPI( title="ProjectName", description="ProjectName Description", ) app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) static_dir = os.path.join(os.path.dirname(__file__), "static") app.mount("/", StaticFiles(directory=static_dir, html=True), name="static") @app.post("/api/devices/connect") async def auth(auth_input: AuthInput): print('API called here.....') ## other codes goes here def start_server(): print("Starting Server...Success") webbrowser.open("http://127.0.0.1:8000/") uvicorn.run( "projectname.main:app", host="0.0.0.0", port=8000, log_level="debug", reload=True, )
安装wheel包时使用的命令:
pip install --extra-index-url projectName.whl
1. 修正路由注册顺序(核心问题)
FastAPI的路由匹配按注册顺序执行,你当前先挂载了根路径/的静态文件服务,它会优先匹配所有请求(包括/api/和/docs),导致API路由被拦截,返回405(静态文件服务不处理POST请求)。
调整代码顺序,先注册所有API路由,再挂载静态文件服务:
app = FastAPI( title="ProjectName", description="ProjectName Description", ) app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # 先注册API路由 @app.post("/api/devices/connect") async def auth(auth_input: AuthInput): print('API called here.....') ## other codes goes here # 再挂载静态文件到根路径 static_dir = os.path.join(os.path.dirname(__file__), "static") app.mount("/", StaticFiles(directory=static_dir, html=True), name="static")
这样FastAPI会先检查请求是否匹配API路由,不匹配时才交由静态文件服务处理。
2. 修正wheel包安装命令
--extra-index-url参数用于指定额外PyPI镜像源,安装本地wheel包直接使用:
pip install projectName.whl
3. 确保静态资源被正确打包进wheel
检查setup.py配置,确保static目录文件被包含到wheel包中:
from setuptools import setup, find_packages setup( name="projectname", version="0.1.0", packages=find_packages(), # 自动包含包内所有数据文件 include_package_data=True, # 显式指定要打包的静态资源 package_data={ "projectname": ["static/**/*"], }, # ...其他配置(如entry_points等) )
若存在MANIFEST.in文件,补充静态资源规则:
recursive-include projectname/static *
4. 验证API路由是否生效
重新生成wheel包并安装后,启动服务访问http://127.0.0.1:8000/openapi.json,若能正常返回JSON格式的API文档,说明API路由已正确注册,此时再测试/api/devices/connect接口和/docs页面即可正常使用。
内容的提问来源于stack exchange,提问作者Rakesh Shetty

