获取 AttributeError:“ASGIRequest”对象在 daphne django 中没有属性“get”
Posted
技术标签:
【中文标题】获取 AttributeError:“ASGIRequest”对象在 daphne django 中没有属性“get”【英文标题】:Getting AttributeError: 'ASGIRequest' object has no attribute 'get' in daphne django 【发布时间】:2021-10-23 21:43:45 【问题描述】:我正在尝试在 daphne 网络服务器而不是 uvicorn 上运行我的 fastapi 代码,因为我的最终目标是在 uvicorn 不可用的 android 上运行它。 此时我已经调试我的应用程序几个小时了。全部设置好。这是我的代码:
settings.py
"""
Django settings for myproject project.
Generated by 'django-admin startproject' using Django 3.2.6.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-_n5hy*-sk6y0&mcgu6&_s*+ql5fvujw+ndccjobc0g8lryx!^z'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'myproject.urls'
TEMPLATES = [
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS':
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
,
,
]
WSGI_APPLICATION = 'myproject.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES =
'default':
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
,
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
,
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
,
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
,
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
ALLOWED_HOSTS = ['*'] #my change
ROOT_URLCONF = "myproject.urlconf" #my change
# Static files (CSS, javascript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
urlconf.py
from django.urls import path
import views
urlpatterns = [
path('coordinates/', views.main),
]
views.py
from fastapi import FastAPI
from datetime import datetime
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware
def main(response):
app = FastAPI()
origins = ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.post("/") #get
def root():
return "message": "Hello World"
directionX = 0
directionY = 0
Gas = 0
@app.get("/coordinates/") #post is used to get data, but I can send it using get and query parameters response_model=Item)
def getcoordinates(direction_x,direction_y,gas): #http://127.0.0.1:8000/coordinates/?direction_x=0&direction_y=10&gas=50
global directionX,directionY, Gas #changed async def to def
directionX = direction_x
directionY = direction_y
Gas = gas
return "data":(direction_x,direction_y,gas)
return HttpResponse(status=200) #works, ok
asgi.py
"""
ASGI config for myproject project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') #myproject.settings
application = get_asgi_application()
启动文件的终端命令:
daphne -b 0.0.0.0 -p 8000 myproject.asgi:application
我在浏览器中访问http://0.0.0.0:8000/coordinates时的错误日志:
2021-08-23 14:00:35,107 INFO Starting server at tcp:port=8000:interface=0.0.0.0
2021-08-23 14:00:35,108 INFO HTTP/2 support not enabled (install the http2 and tls Twisted extras)
2021-08-23 14:00:35,108 INFO Configuring endpoint tcp:port=8000:interface=0.0.0.0
2021-08-23 14:00:35,109 INFO Listening on TCP address 0.0.0.0:8000
Internal Server Error: /coordinates/
Traceback (most recent call last):
File "/home/petr/.local/lib/python3.8/site-packages/asgiref/sync.py", line 482, in thread_handler
raise exc_info[1]
File "/home/petr/.local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 38, in inner
response = await get_response(request)
File "/home/petr/.local/lib/python3.8/site-packages/django/utils/deprecation.py", line 135, in __acall__
response = await sync_to_async(
File "/home/petr/.local/lib/python3.8/site-packages/asgiref/sync.py", line 444, in __call__
ret = await asyncio.wait_for(future, timeout=None)
File "/usr/lib/python3.8/asyncio/tasks.py", line 455, in wait_for
return await fut
File "/usr/lib/python3.8/concurrent/futures/thread.py", line 57, in run
result = self.fn(*self.args, **self.kwargs)
File "/home/petr/.local/lib/python3.8/site-packages/asgiref/sync.py", line 486, in thread_handler
return func(*args, **kwargs)
File "/home/petr/.local/lib/python3.8/site-packages/django/middleware/clickjacking.py", line 26, in process_response
if response.get('X-Frame-Options') is not None:
AttributeError: 'ASGIRequest' object has no attribute 'get'
2021-08-23 14:00:45,987 ERROR Internal Server Error: /coordinates/
Traceback (most recent call last):
File "/home/petr/.local/lib/python3.8/site-packages/asgiref/sync.py", line 482, in thread_handler
raise exc_info[1]
File "/home/petr/.local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 38, in inner
response = await get_response(request)
File "/home/petr/.local/lib/python3.8/site-packages/django/utils/deprecation.py", line 135, in __acall__
response = await sync_to_async(
File "/home/petr/.local/lib/python3.8/site-packages/asgiref/sync.py", line 444, in __call__
ret = await asyncio.wait_for(future, timeout=None)
File "/usr/lib/python3.8/asyncio/tasks.py", line 455, in wait_for
return await fut
File "/usr/lib/python3.8/concurrent/futures/thread.py", line 57, in run
result = self.fn(*self.args, **self.kwargs)
File "/home/petr/.local/lib/python3.8/site-packages/asgiref/sync.py", line 486, in thread_handler
return func(*args, **kwargs)
File "/home/petr/.local/lib/python3.8/site-packages/django/middleware/clickjacking.py", line 26, in process_response
if response.get('X-Frame-Options') is not None:
AttributeError: 'ASGIRequest' object has no attribute 'get'
127.0.0.1:58158 - - [23/Aug/2021:14:00:45] "GET /coordinates/" 500 76195
Not Found: /favicon.ico
2021-08-23 14:00:46,611 WARNING Not Found: /favicon.ico
127.0.0.1:58158 - - [23/Aug/2021:14:00:46] "GET /favicon.ico" 404 2120
非常感谢任何可以帮助我的人!
【问题讨论】:
Django 中的 FastAPI? ?????? @JPG 是的,因为 fastapi 无法自行运行。它需要 uvicorn 或 daphne(在 django 下运行)才能运行。现在我请求你删除你的反对票。 【参考方案1】:Daphne 由 Django 项目维护,但您可以自行安装。要安装它,首先切换到您的虚拟环境(如果您正在使用),然后运行:
python -m pip install daphne
然后将 FastAPI 代码从 Django 视图中删除到它自己的文件中,例如main.py
from fastapi import FastAPI
from datetime import datetime
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
origins = ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.post("/") #get
def root():
return "message": "Hello World"
...
现在,如果您切换到与 main.py
相同的目录,您可以使用以下命令运行您的文件:
daphne -b 0.0.0.0 -p 8000 main:app
【讨论】:
你好。我一直在尝试将此 daphne 服务器与 pagekite 一起使用,以使其可以从任何地方访问。我试过 python3 pagekite.py --frontend=something.pagekite.me --service_on=0.0.0.0:8000 并且python控制台说:〜``` Flying builtin HTTPD as something.pagekite.me:8080 - something.pagekite.me:8080 93.153.49.187 something.pagekite.me:8080 (builtin) 当我转到 0.0.0.0:8000/coordinates/… 时,我得到了预期的 json。当我去 something.pagekite.me:8080/coordinates/?direction_x=1&direction_y=2&gas=52 我得到错误 404 你能帮忙吗? 这听起来像是一个单独的问题,而且我之前没有使用过 pagekite,所以我恐怕无法帮助您以上是关于获取 AttributeError:“ASGIRequest”对象在 daphne django 中没有属性“get”的主要内容,如果未能解决你的问题,请参考以下文章
AttributeError: 'property' 对象没有属性 'copy' - 尝试在 Django Rest 中获取对象列表时
获取 AttributeError: 'dict' object has no attribute 'parse' 。尝试读入多个 xlsx 文件时
获取 AttributeError:“OneHotEncoder”对象没有属性“pyspark 中的 _jdf”
AttributeError:无法在 <module 'gensim.models.word2vec' 上获取属性 'Vocab'
Django Rest with JWT,获取 AttributeError:无效的 API 设置:'JWT_PAYLOAD_HANDLER'