gpt4 book ai didi

python - 断言isinstance(地址,(元组,列表,str)), "tuple or str expected"AssertionError : tuple or str expected

转载 作者:行者123 更新时间:2023-12-01 01:28:16 26 4
gpt4 key购买 nike

我正在开发一个 django 项目,其中包含 django channel ,但出现此错误。我尝试修复该错误,但问题是我无法真正找到我的程序有问题的地方。

#views.py
from django.shortcuts import render, get_object_or_404
from django.views.generic import View
from django.http import HttpResponse, HttpResponseRedirect
from Forecast.models import*
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync #this is to help us convert the
asyncrounous request to a syncronous one

class Home(View):
def get(self, request):
houses = House.objects.all()
context={'houses':houses}
layer = get_channel_layer()
async_to_sync(layer.group_send)(
'visted', {
'type':'homepage.visted',
'event':'new visit',
'username':request.user.username
})
return render(request,'accounts/base.html',context)

那么下面是我的consumer.py

#consumer.py
from channels.generic.websocket import AsyncWebsocketConsumer
import asyncio

class TestConsumer(AsyncWebsocketConsumer):
async def connect(self):
#this accepts the connection
await self.accept()
await self.channel_layer.group_add('visted', self.channel_name)
await asyncio.sleep(4)
await self.send(text_data='you have been connected')
async def receive(self, test_data=None, byte_data=None):
#this handles all received data
await self.send(text_data= 'we got your message')
await asyncio.sleep(4)
await self.close()
async def disconnect(self):
await self.channel_layer.group_discard('visited', self.channel_name)
async def hompage_visted(self, event):
await self.send(text_data=event['message'])

最后是我的routing.py,asgi路由文件

#routing.py
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from django.urls import path
from .consumer import TestConsumer

application = ProtocolTypeRouter({
"websocket": AuthMiddlewareStack(
URLRouter([
path('testsocket/', TestConsumer)
])
)
})

但就像我说的那样,我不断收到此错误,下面我发现有一个指向我的views.py的链接,但我无法弄清楚代码出了什么问题

Traceback:

File "C:\Users\LIVINUS\AppData\Local\Programs\Python\Python36\lib\site-
packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)

File "C:\Users\LIVINUS\AppData\Local\Programs\Python\Python36\lib\site-
packages\django\core\handlers\base.py" in _get_response
126. response = self.process_exception_by_middleware(e,
request)

File "C:\Users\LIVINUS\AppData\Local\Programs\Python\Python36\lib\site-
packages\django\core\handlers\base.py" in _get_response
124. response = wrapped_callback(request, *callback_args,
**callback_kwargs)

File "C:\Users\LIVINUS\AppData\Local\Programs\Python\Python36\lib\site-
packages\django\views\generic\base.py" in view
68. return self.dispatch(request, *args, **kwargs)

File "C:\Users\LIVINUS\AppData\Local\Programs\Python\Python36\lib\site-
packages\django\views\generic\base.py" in dispatch
88. return handler(request, *args, **kwargs)

File "C:\Projects\Hagent\Hagent\views.py" in get
18. 'username':request.user.username

File "C:\Users\LIVINUS\AppData\Local\Programs\Python\Python36\lib\site-
packages\asgiref\sync.py" in __call__
64. return call_result.result()

File
"C:\Users\LIVINUS\AppData\Local\Programs\Python\Python36\lib\concurrent\
futures\_base.py" in result
432. return self.__get_result()

File
"C:\Users\LIVINUS\AppData\Local\Programs\Python\Python36\lib\concurrent\
futures\_base.py" in __get_result
384. raise self._exception

File "C:\Users\LIVINUS\AppData\Local\Programs\Python\Python36\lib\site-
packages\asgiref\sync.py" in main_wrap
78. result = await self.awaitable(*args, **kwargs)

File "C:\Users\LIVINUS\AppData\Local\Programs\Python\Python36\lib\site-
packages\channels_redis-2.3.1-py3.6.egg\channels_redis\core.py" in
group_send
601. async with self.connection(self.consistent_hash(group)) as
connection:

File "C:\Users\LIVINUS\AppData\Local\Programs\Python\Python36\lib\site-
packages\channels_redis-2.3.1-py3.6.egg\channels_redis\core.py" in
__aenter__
813. self.conn = await self.pool.pop()

File "C:\Users\LIVINUS\AppData\Local\Programs\Python\Python36\lib\site-
packages\channels_redis-2.3.1-py3.6.egg\channels_redis\core.py" in pop
70. conns.append(await aioredis.create_redis(**self.host,
loop=loop))

File "C:\Users\LIVINUS\AppData\Local\Programs\Python\Python36\lib\site-
packages\aioredis-1.2.0-py3.6.egg\aioredis\commands\__init__.py" in
create_redis
178. loop=loop)

File "C:\Users\LIVINUS\AppData\Local\Programs\Python\Python36\lib\site-
packages\aioredis-1.2.0-py3.6.egg\aioredis\connection.py" in
create_connection
77. assert isinstance(address, (tuple, list, str)), "tuple or str
expected"

Exception Type: AssertionError at /
Exception Value: tuple or str expected

在我的settings.py中

INSTALLED_APPS = [
#django specific apps
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
#here are my own apps
'Account.apps.AccountConfig',
'Forecast.apps.ForecastConfig',
#here are third party apps
'rest_framework',
'AutoTags',
'channels',
]

WSGI_APPLICATION = os.path.split(BASE_DIR)[1]+'.wsgi.application'
ASGI_APPLICATION = os.path.split(BASE_DIR)[1]+'.routing.application'



DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}

CHANNEL_LAYERS={
'default':{
'BACKEND':'channels_redis.core.RedisChannelLayer',
'CONFIG':{
'hosts':['localhost', 6379]
}
},
}

最佳答案

所以问题出在不正确的 settings.CHANNEL_LAYERS 变量中。

hosts 应该是一个包含元组的列表。

CHANNEL_LAYERS={
'default': {
'BACKEND':'channels_redis.core.RedisChannelLayer',
'CONFIG':{
'hosts': [('localhost', 6379)],
}
},
}

Reference

关于python - 断言isinstance(地址,(元组,列表,str)), "tuple or str expected"AssertionError : tuple or str expected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53150511/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com