在Django频道中创建多个Communicator

时间:2019-01-20 00:01:45

标签: django python-asyncio django-channels

我正在测试使用Django Channels构建的Chat应用程序,并且尝试创建2个用于对2个用户进行建模的传播者,但是在实例化第二个传播者的那一行中,我一直得到psycopg2.InterfaceError: connection already closed。这是我所拥有的:

async def test_chat(self):
    await self.set_up()
    communicator = WebsocketCommunicator(application, self.endpoint)
    await communicator.connect()
    await communicator.receive_from()

    communicator2 = WebsocketCommunicator(application, self.endpoint2)
    await communicator2.connect()
    await communicator2.receive_from()

仅使用一个通讯器就可以正常工作,但是我需要2个才能正确测试它。这不可能吗?或者我想念什么吗?

这是stacktrace的样子。

    >       communicator2 = WebsocketCommunicator(application, self.endpoint2)

test_consumers.py:282: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
/home/kenneth/.virtualenvs/weout/lib/python3.6/site-packages/channels/testing/websocket.py:26: in __init__
    super().__init__(application, self.scope)
/home/kenneth/.virtualenvs/weout/lib/python3.6/site-packages/asgiref/testing.py:17: in __init__
    self.instance = self.application(scope)
/home/kenneth/.virtualenvs/weout/lib/python3.6/site-packages/channels/routing.py:58: in __call__
    return self.application_mapping[scope["type"]](scope)
/home/kenneth/.virtualenvs/weout/lib/python3.6/site-packages/channels/security/websocket.py:37: in __call__
    return self.application(scope)
../../weout/messaging/authentication.py:40: in __call__
    user_auth_tuple = authenticator.authenticate(request)
../../weout/accounts/authentication.py:44: in authenticate
    self.authenticate_client(request)
../../weout/accounts/authentication.py:90: in authenticate_client
    client = self.client_model.objects.get(client_id=client_id, client_secret=client_secret)
/home/kenneth/.virtualenvs/weout/lib/python3.6/site-packages/django/db/models/manager.py:82: in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
/home/kenneth/.virtualenvs/weout/lib/python3.6/site-packages/django/db/models/query.py:397: in get
    num = len(clone)
/home/kenneth/.virtualenvs/weout/lib/python3.6/site-packages/django/db/models/query.py:254: in __len__
    self._fetch_all()
/home/kenneth/.virtualenvs/weout/lib/python3.6/site-packages/django/db/models/query.py:1179: in _fetch_all
    self._result_cache = list(self._iterable_class(self))
/home/kenneth/.virtualenvs/weout/lib/python3.6/site-packages/django/db/models/query.py:53: in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
/home/kenneth/.virtualenvs/weout/lib/python3.6/site-packages/django/db/models/sql/compiler.py:1066: in execute_sql
    cursor = self.connection.cursor()
/home/kenneth/.virtualenvs/weout/lib/python3.6/site-packages/django/db/backends/base/base.py:255: in cursor
    return self._cursor()
/home/kenneth/.virtualenvs/weout/lib/python3.6/site-packages/django/db/backends/base/base.py:234: in _cursor
    return self._prepare_cursor(self.create_cursor(name))
/home/kenneth/.virtualenvs/weout/lib/python3.6/site-packages/django/db/utils.py:89: in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
/home/kenneth/.virtualenvs/weout/lib/python3.6/site-packages/django/db/backends/base/base.py:234: in _cursor
    return self._prepare_cursor(self.create_cursor(name))
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <django.contrib.gis.db.backends.postgis.base.DatabaseWrapper object at 0x7faa17c7eef0>
name = None

    def create_cursor(self, name=None):
        if name:
            # In autocommit mode, the cursor will be used outside of a
            # transaction, hence use a holdable cursor.
            cursor = self.connection.cursor(name, scrollable=False, withhold=self.connection.autocommit)
        else:
>           cursor = self.connection.cursor()
E           django.db.utils.InterfaceError: connection already closed

基本上,它到达了调用我的身份验证器并尝试进行数据库调用的地步。从stacktrace可以看出,它从我实例化第二个通信器的那一行开始。

communicator2 = WebsocketCommunicator(application, self.endpoint2)

实例化第一个传播者却没有给出这样的错误

1 个答案:

答案 0 :(得分:0)

import json dict_type = {"enTitle": "my product", "esTitle": "es prod", "esDescription": "es description", "enDescription": "description", "URL": "url", "Image": "imagepath", "HasLandingPage": "1", "AddInfo": "info" } def check_type(var): if isinstance(var, str): return 'string' elif isinstance(var, int): return 'interger' elif isinstance(var, float): return 'float' elif isinstance(var, bool): return 'boolean' swift_type = list() for key,val in dict_type.items(): swift_type.append({"name": key, "value": val, "type": check_type(val)}) print(*swift_type, sep='\n') # Coverted to json swift_type = json.dumps(swift_type) 固定装置中添加transaction=True解决了该问题。出于某种原因,我从未想过