assert isinstance(地址,(tuple,list,str)),“ tuple或str预期” AssertionError:tuple或str预期

时间:2018-11-05 08:10:39

标签: python django async-await asyncsocket django-channels

我正在一个django项目中,其中包括了django通道,但出现此错误。我已尝试修复该错误,但问题是我无法真正找到程序存在问题的地方。

#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)

然后这是我的消费者。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]
            }
    },
}

2 个答案:

答案 0 :(得分:1)

因此问题出在错误的settings.CHANNEL_LAYERS变量中。

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

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

Reference

答案 1 :(得分:0)

@Satevg所说的完全正确。它应该是包含元组的列表。

但是有时使用本地主机会有一些问题。

最好拥有IP。

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