当前位置: 首页>>代码示例>>Python>>正文


Python db.database_sync_to_async方法代码示例

本文整理汇总了Python中channels.db.database_sync_to_async方法的典型用法代码示例。如果您正苦于以下问题:Python db.database_sync_to_async方法的具体用法?Python db.database_sync_to_async怎么用?Python db.database_sync_to_async使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在channels.db的用法示例。


在下文中一共展示了db.database_sync_to_async方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_updates_lastseen

# 需要导入模块: from channels import db [as 别名]
# 或者: from channels.db import database_sync_to_async [as 别名]
def test_updates_lastseen(self):
        async with Communicator() as communicator:
            user = await AsyncUserFactory()
            communicator.scope['user'] = user
            await communicator.connect()

            # update the lastseen timestamp to ages ago
            the_past = timezone.now() - relativedelta(hours=6)
            await database_sync_to_async(ChannelSubscription.objects.filter(user=user).update)(lastseen_at=the_past)

            await communicator.send_json_to({'message': 'hey'})
            await asyncio.sleep(0.1)

            subscription = (await get_subscription(user=user))[0]
            difference = subscription.lastseen_at - the_past
            assert difference.total_seconds() > 1000 
开发者ID:yunity,项目名称:karrot-backend,代码行数:18,代码来源:test_consumers.py

示例2: init

# 需要导入模块: from channels import db [as 别名]
# 或者: from channels.db import database_sync_to_async [as 别名]
def init(self):
        cases = await database_sync_to_async(SubmissionCase.objects.filter)(submission=self.submission)
        await self.update_result(
            event={
                'data': UpdatingData(
                    result=self.submission.result.result.full,
                    code=self.submission.code,
                    case_number=self.submission.attach_info.cases_count,
                    submit_time=self.submission.create_time.strftime("%Y-%m-%d %H:%M:%S"),
                    language=self.submission.language.full,
                    compile_info=self.submission.result.compile_info,
                    error_info=self.submission.result.error_info,
                    problem_title=self.submission.problem.title,
                    problem_slug=self.submission.problem.slug,
                    submit_user=self.submission.user.username,
                    case_list=[CaseData(
                        result=each.result.full,
                        time_cost=each.time_cost,
                        memory_cost=each.memory_cost,
                        case=each.case
                    ) for each in cases]
                ).serialization()
            }
        ) 
开发者ID:lutece-awesome,项目名称:lutece-backend,代码行数:26,代码来源:consumers.py

示例3: _run_on_infrastructure

# 需要导入模块: from channels import db [as 别名]
# 或者: from channels.db import database_sync_to_async [as 别名]
def _run_on_infrastructure(meth, *args, **kwargs):
    """Start the Manager infrastructure and call the given callable.

    The method given is run through a serializing wrapper, so that
    Django database accesses are correct.

    :param meth: The callable to run on the infrastructure. All other
        arguments are forwarded to it.
    """
    with TestingContext():
        _create_test_dirs()
        with _prepare_settings():
            storage_config = copy.deepcopy(STORAGE_CONNECTORS)
            storage_config[STORAGE_LOCAL_CONNECTOR]["config"][
                "path"
            ] = settings.FLOW_EXECUTOR["DATA_DIR"]
            with patch("resolwe.storage.settings.STORAGE_CONNECTORS", storage_config):
                connectors.recreate_connectors()
                await database_sync_to_async(_manager_setup)()
                with AtScopeExit(manager.state.destroy_channels):
                    redis_params = getattr(settings, "FLOW_MANAGER", {}).get(
                        "REDIS_CONNECTION", {}
                    )
                    listener = ExecutorListener(redis_params=redis_params)
                    await listener.clear_queue()
                    async with listener:
                        try:
                            with override_settings(FLOW_MANAGER_SYNC_AUTO_CALLS=True):
                                result = await database_sync_to_async(meth)(
                                    *args, **kwargs
                                )
                            return result
                        finally:
                            listener.terminate() 
开发者ID:genialis,项目名称:resolwe,代码行数:36,代码来源:test_runner.py

示例4: __aenter__

# 需要导入模块: from channels import db [as 别名]
# 或者: from channels.db import database_sync_to_async [as 别名]
def __aenter__(self):
        user = await AsyncUserFactory()
        token = await database_sync_to_async(Token.objects.create)(user=user)
        encoded = b64encode(token.key.encode('ascii')).decode('ascii')
        self.communicator = WebsocketCommunicator(
            TokenAuthMiddleware(WebsocketConsumer),
            '/',
            subprotocols=['karrot.token', 'karrot.token.value.{}'.format(encoded.rstrip('='))],
        )
        return self.communicator, user 
开发者ID:yunity,项目名称:karrot-backend,代码行数:12,代码来源:test_consumers.py

示例5: test_updates_away

# 需要导入模块: from channels import db [as 别名]
# 或者: from channels.db import database_sync_to_async [as 别名]
def test_updates_away(self):
        async with Communicator() as communicator:
            user = await AsyncUserFactory()
            communicator.scope['user'] = user
            await communicator.connect()

            await communicator.send_json_to({'type': 'away'})
            await asyncio.sleep(0.1)
            subscription = (await get_subscription(user=user))[0]
            assert subscription.away_at is not None

            await communicator.send_json_to({'type': 'back'})
            await asyncio.sleep(0.1)
            await database_sync_to_async(subscription.refresh_from_db)()
            assert subscription.away_at is None 
开发者ID:yunity,项目名称:karrot-backend,代码行数:17,代码来源:test_consumers.py

示例6: resolve_scope

# 需要导入模块: from channels import db [as 别名]
# 或者: from channels.db import database_sync_to_async [as 别名]
def resolve_scope(self, scope):
        token = get_auth_token_from_subprotocols(scope.get('subprotocols', []))
        if token:
            user, _ = await database_sync_to_async(token_auth.authenticate_credentials)(token)
            if user:
                scope['user']._wrapped = user 
开发者ID:yunity,项目名称:karrot-backend,代码行数:8,代码来源:consumers.py

示例7: action

# 需要导入模块: from channels import db [as 别名]
# 或者: from channels.db import database_sync_to_async [as 别名]
def action(atomic=None, **kwargs):
    """
    Mark a method as an action.
    """

    def decorator(func):
        if atomic is None:
            _atomic = getattr(settings, "ATOMIC_REQUESTS", False)
        else:
            _atomic = atomic

        func.action = True
        func.kwargs = kwargs
        if asyncio.iscoroutinefunction(func):
            if _atomic:
                raise ValueError("Only synchronous actions can be atomic")
            return func

        if _atomic:
            # wrap function in atomic wrapper
            func = transaction.atomic(func)

        @wraps(func)
        async def async_f(self: AsyncAPIConsumer, *args, **_kwargs):

            result, status = await database_sync_to_async(func)(self, *args, **_kwargs)

            return result, status

        async_f.action = True
        async_f.kwargs = kwargs
        async_f.__name__ = func.__name__

        return async_f

    return decorator 
开发者ID:hishnash,项目名称:djangochannelsrestframework,代码行数:38,代码来源:decorators.py

示例8: subscribe_instance

# 需要导入模块: from channels import db [as 别名]
# 或者: from channels.db import database_sync_to_async [as 别名]
def subscribe_instance(self, request_id=None, **kwargs):
        if request_id is None:
            raise ValueError("request_id must have a value set")
        # subscribe!
        instance = await database_sync_to_async(self.get_object)(**kwargs)
        await self.handle_instance_change.subscribe(instance=instance)
        self.subscribed_requests[self.__class__.handle_instance_change] = request_id

        return None, status.HTTP_201_CREATED 
开发者ID:hishnash,项目名称:djangochannelsrestframework,代码行数:11,代码来源:generics.py

示例9: unsubscribe_instance

# 需要导入模块: from channels import db [as 别名]
# 或者: from channels.db import database_sync_to_async [as 别名]
def unsubscribe_instance(self, request_id=None, **kwargs):
        if request_id is None:
            raise ValueError("request_id must have a value set")
        # subscribe!
        instance = await database_sync_to_async(self.get_object)(**kwargs)
        await self.handle_instance_change.unsubscribe(instance=instance)
        del self.subscribed_requests[self.__class__.handle_instance_change]

        return None, status.HTTP_204_NO_CONTENT 
开发者ID:hishnash,项目名称:djangochannelsrestframework,代码行数:11,代码来源:generics.py

示例10: ensure_async

# 需要导入模块: from channels import db [as 别名]
# 或者: from channels.db import database_sync_to_async [as 别名]
def ensure_async(method: typing.Callable):
    if asyncio.iscoroutinefunction(method):
        return method
    return database_sync_to_async(method) 
开发者ID:hishnash,项目名称:djangochannelsrestframework,代码行数:6,代码来源:consumers.py

示例11: test_observer_wrapper

# 需要导入模块: from channels import db [as 别名]
# 或者: from channels.db import database_sync_to_async [as 别名]
def test_observer_wrapper(settings):
    settings.CHANNEL_LAYERS = {
        "default": {
            "BACKEND": "channels.layers.InMemoryChannelLayer",
            "TEST_CONFIG": {"expiry": 100500,},
        },
    }

    layer = channel_layers.make_test_backend(DEFAULT_CHANNEL_LAYER)

    class TestConsumer(AsyncAPIConsumer):
        async def accept(self):
            await self.handle_user_logged_in.subscribe()
            await super().accept()

        @observer(user_logged_in)
        async def handle_user_logged_in(self, *args, observer=None, **kwargs):
            await self.send_json({"message": kwargs, "observer": observer is not None})

    communicator = WebsocketCommunicator(TestConsumer, "/testws/")

    connected, _ = await communicator.connect()

    assert connected

    user = await database_sync_to_async(get_user_model().objects.create)(
        username="test", email="test@example.com"
    )

    await database_sync_to_async(user_logged_in.send)(
        sender=user.__class__, request=None, user=user
    )

    response = await communicator.receive_json_from()

    assert {"message": {}, "observer": True} == response

    await communicator.disconnect() 
开发者ID:hishnash,项目名称:djangochannelsrestframework,代码行数:40,代码来源:test_observer.py

示例12: test_model_observer_delete_wrapper

# 需要导入模块: from channels import db [as 别名]
# 或者: from channels.db import database_sync_to_async [as 别名]
def test_model_observer_delete_wrapper(settings):
    settings.CHANNEL_LAYERS = {
        "default": {
            "BACKEND": "channels.layers.InMemoryChannelLayer",
            "TEST_CONFIG": {"expiry": 100500,},
        },
    }

    layer = channel_layers.make_test_backend(DEFAULT_CHANNEL_LAYER)

    class TestConsumer(AsyncAPIConsumer):
        async def accept(self):
            await TestConsumer.user_change.subscribe(self)
            await super().accept()

        @model_observer(get_user_model())
        async def user_change(self, message, observer=None, **kwargs):
            await self.send_json(message)

    communicator = WebsocketCommunicator(TestConsumer, "/testws/")

    connected, _ = await communicator.connect()

    assert connected
    user = await database_sync_to_async(get_user_model())(
        username="test", email="test@example.com"
    )
    await database_sync_to_async(user.save)()

    response = await communicator.receive_json_from()

    assert {"action": "create", "pk": user.pk, "type": "user.change"} == response
    pk = user.pk

    await database_sync_to_async(user.delete)()

    response = await communicator.receive_json_from()

    assert {"action": "delete", "pk": pk, "type": "user.change"} == response

    await communicator.disconnect() 
开发者ID:hishnash,项目名称:djangochannelsrestframework,代码行数:43,代码来源:test_observer.py

示例13: _get_request_dict

# 需要导入模块: from channels import db [as 别名]
# 或者: from channels.db import database_sync_to_async [as 别名]
def _get_request_dict(self, pk=None, user=None):
        if not pk:
            location = await database_sync_to_async(self._create_location)(
                is_mobile=True
            )
            await database_sync_to_async(self._create_object_location)(
                location=location
            )
            pk = location.pk
        path = '/ws/loci/location/{0}/'.format(pk)
        session = None
        if user:
            session = await database_sync_to_async(self._force_login)(user)
        return {'pk': pk, 'path': path, 'session': session} 
开发者ID:openwisp,项目名称:openwisp-controller,代码行数:16,代码来源:pytest.py

示例14: test_consumer_staff_but_no_change_permission

# 需要导入模块: from channels import db [as 别名]
# 或者: from channels.db import database_sync_to_async [as 别名]
def test_consumer_staff_but_no_change_permission(self):
        user = await database_sync_to_async(self.user_model.objects.create_user)(
            username='user', password='password', email='test@test.org', is_staff=True
        )
        location = await database_sync_to_async(self._create_location)(is_mobile=True)
        await database_sync_to_async(self._create_object_location)(location=location)
        pk = location.pk
        request_vars = await self._get_request_dict(user=user, pk=pk)
        communicator = self._get_communicator(request_vars, user)
        connected, _ = await communicator.connect()
        assert not connected
        await communicator.disconnect()
        # add permission to change location and repeat
        perm = await database_sync_to_async(
            (
                await database_sync_to_async(Permission.objects.filter)(
                    name='Can change location'
                )
            ).first
        )()
        await database_sync_to_async(user.user_permissions.add)(perm)
        user = await database_sync_to_async(self.user_model.objects.get)(pk=user.pk)
        request_vars = await self._get_request_dict(user=user, pk=pk)
        communicator = self._get_communicator(request_vars, user)
        connected, _ = await communicator.connect()
        assert not connected
        await communicator.disconnect()
        # add user to organization
        await database_sync_to_async(location.organization.add_user)(user)
        await database_sync_to_async(location.organization.save)()
        user = await database_sync_to_async(self.user_model.objects.get)(pk=user.pk)
        request_vars = await self._get_request_dict(user=user, pk=pk)
        communicator = self._get_communicator(request_vars, user)
        connected, _ = await communicator.connect()
        assert connected
        await communicator.disconnect() 
开发者ID:openwisp,项目名称:openwisp-controller,代码行数:38,代码来源:pytest.py

示例15: receive_json

# 需要导入模块: from channels import db [as 别名]
# 或者: from channels.db import database_sync_to_async [as 别名]
def receive_json(self, content):
        action = content.get('action')
        if action == 'authenticate':
            if self.app:
                await self.respond('invalid_payload', d='already authenticated')
                return

            token = content.get('token')
            if not token:
                await self.respond('invalid_payload', d='no token was provided')
                return

            self.app = await database_sync_to_async(Application.get_by_token)(token)
            if not self.app:
                await self.respond('invalid_token')
                return

            self.channels = [channel.name.lower() for channel in await database_sync_to_async(self.app.channels.all)()]
            await self.respond('authenticated', name=self.app.name, slug=self.app.slug, channels=self.channels)

        elif action == 'message':
            await self.respond(await database_sync_to_async(handle_message_action)(self.app, content))

        else:
            await self.respond('invalid_payload', d='invalid action')
            return 
开发者ID:devunt,项目名称:ika,代码行数:28,代码来源:controllers.py


注:本文中的channels.db.database_sync_to_async方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。