Django使用Daphne运行FastAPI报ASGIRequest无get属性错误
问题根因
你当前的错误和集成逻辑有三处核心问题:
- Django视图基础错误:视图函数的第一个入参是
request请求对象,你误写为response,且未导入HttpResponse就直接返回,导致Django拿到的响应对象非法,中间件处理时触发属性不存在报错。 - FastAPI集成逻辑错误:不能在Django视图内每次请求都实例化FastAPI,这会导致性能极低且FastAPI路由完全没有生效,你没有做任何请求转发逻辑。
- ASGI配置错误:Daphne当前仅启动了Django服务,没有挂载FastAPI应用,你的FastAPI逻辑完全没有被服务加载。
修复步骤
1. 重写views.py
将FastAPI实例化移到全局作用域,补全缺失的导入:
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from django.http import HttpResponse # 全局初始化FastAPI,不要放在视图函数内重复创建 app = FastAPI() origins = ["*"] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) directionX = 0 directionY = 0 Gas = 0 @app.post("/") def root(): return {"message": "Hello World"} @app.get("/coordinates/") def getcoordinates(direction_x: str, direction_y: str, gas: str): global directionX, directionY, Gas directionX = direction_x directionY = direction_y Gas = gas return {"data": (direction_x, direction_y, gas)}
2. 修改asgi.py,挂载FastAPI应用
让Daphne可以同时处理FastAPI和Django的请求:
import os from django.core.asgi import get_asgi_application from fastapi.middleware.wsgi import WSGIMiddleware # 导入你定义的FastAPI实例 from .views import app as fastapi_app os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') django_app = get_asgi_application() # 把Django服务挂载到/django路径下,其他路径请求均走FastAPI fastapi_app.mount("/django", WSGIMiddleware(django_app)) application = fastapi_app
3. 清理无效Django路由
删除urlconf.py中path('coordinates/', views.main)这一行配置,FastAPI的路由不需要走Django分发。
4. 验证效果
启动命令保持不变:
daphne -b 0.0.0.0 -p 8000 myproject.asgi:application
访问http://127.0.0.1:8000/coordinates/?direction_x=0&direction_y=10&gas=50即可得到正确返回。
内容的提问来源于stack exchange,提问作者Petr L.
相关产品推荐
相关产品推荐

