Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 断言isinstance(地址,(元组,列表,str)),“;应为元组或str“;AssertionError:应为元组或str_Python_Django_Async Await_Asyncsocket_Django Channels - Fatal编程技术网

Python 断言isinstance(地址,(元组,列表,str)),“;应为元组或str“;AssertionError:应为元组或str

Python 断言isinstance(地址,(元组,列表,str)),“;应为元组或str“;AssertionError:应为元组或str,python,django,async-await,asyncsocket,django-channels,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.mod

我正在从事一个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)
下面是我的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'])
最后是my 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
在my 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]
            }
    },
}

因此,问题出在不正确的
设置中。通道\u层
变量

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


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

但有时使用localhost会出现一些问题

最好换成IP

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

显示您的
设置。py
配置也请注意此错误似乎与您发布的代码无关,但与Redis的设置有关。请出示这些。我已经包括了settings@Nolwac,在您的
设置中。频道\u层
['localhost',6379]
更改为
[('localhost',6379)]
哇!非常感谢,真不敢相信我竟然没有注意到。分享一个问题确实是最好的。再次感谢,我知道这篇文章已经快一年了,但是你帮我省下了几个小时的疑难解答。非常感谢。
  CHANNEL_LAYERS={
  'default': {
      'BACKEND':'channels_redis.core.RedisChannelLayer',
      'CONFIG':{
          'hosts': [('127.0.0.1', 6379)],
      }
   },                                                                    
}