如果该函数缺少 print() 语句,则无法在 Python 中正确操作

If the function lacks a print() statement, it fails to operate correctly in Python

提问人:najam iqbal 提问时间:11/15/2023 最后编辑:najam iqbal 更新时间:11/16/2023 访问量:41

问:

我正在使用 Django 通道,在其中我正在创建一个可以从数据库中获取数据的函数,但问题是当我将该函数与装饰器一起使用时,它不起作用,直到我放入带有查询输出结果的 print 语句。另一方面,它给出了我试图向用户发送消息的错误。@database_sync_to_asyncYou cannot call this from an async context - use a thread or sync_to_async.

提到了代码,其中我突出显示了没有语句就无法工作的函数。print()

@database_sync_to_async
    def get_driver_data(self,data):
        driver = DriverAdditional.objects.get(user_id=data)
        return driver
    
    @database_sync_to_async
    def **get_driver_location**(self,data):
        location = CabLocation.objects.get(driver_id=data)
        **#print(location)**
        return location
    
    
    async def send_amount(self, text_data):
        print("send amount")
        user = self.scope['user'].id
        print("user",user)
        driver = await self.get_driver_data(user)
        message = json.loads(text_data)
        data = message.get('data')
        try:
            location = await self.get_driver_location(driver)
            print(location)
        except Exception as e:
            print(f'error is {e}')
        # print(data['rider'])
        await self.channel_layer.group_send(
            group=data['rider'],
            message = {
                'type': 'echo.message',
                'message_type': 'send_amount',
                'data': f"{driver} {data['amount']}",
            }
        )

没有语句的错误是:print()

> Exception inside application: You cannot call this from an async context - use a thread or sync_to_async.
> Traceback (most recent call last):
> File "D:\Najam\June\development\backend\Lib\site-packages\django\db\models\fields\related_descriptors.py", line 218, in __get__
> rel_obj = self.field.get_cached_value(instance)
>               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
> File "D:\Najam\June\development\backend\Lib\site-packages\django\db\models\fields\mixins.py", line 15, in get_cached_value
> return instance._state.fields_cache[cache_name]
>            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^
> KeyError: 'driver_id'
> 
> During handling of the above exception, another exception occurred:
> 
> Traceback (most recent call last):
> File "D:\Najam\June\development\backend\Lib\site-packages\django\contrib\staticfiles\handlers.py", line 101, in __call__
> return await self.application(scope, receive, send)
>            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
> File "D:\Najam\June\development\backend\Lib\site-packages\channels\routing.py", line 62, in __call__
> return await application(scope, receive, send)
>            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
> File "D:\Najam\June\development\backend\Lib\site-packages\channels\sessions.py", line 47, in __call__
> return await self.inner(dict(scope, cookies=cookies), receive, send)
>            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
> File "D:\Najam\June\development\backend\Lib\site-packages\channels\sessions.py", line 263, in __call__
> return await self.inner(wrapper.scope, receive, wrapper.send)
>            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
> File "D:\Najam\June\development\backend\Lib\site-packages\channels\auth.py", line 185, in __call__
> return await super().__call__(scope, receive, send)
>            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
> File "D:\Najam\June\development\backend\Lib\site-packages\channels\middleware.py", line 24, in __call__
> return await self.inner(scope, receive, send)
>            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
> File "D:\Najam\June\development\backend\Lib\site-packages\channels\routing.py", line 116, in __call__
> return await application(
>            ^^^^^^^^^^^^^^^^^^
> File "D:\Najam\June\development\backend\Lib\site-packages\channels\consumer.py", line 94, in app
> return await consumer(scope, receive, send)
>            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
> File "D:\Najam\June\development\backend\Lib\site-packages\channels\consumer.py", line 58, in __call__
> await await_many_dispatch(
> File "D:\Najam\June\development\backend\Lib\site-packages\channels\utils.py", line 50, in await_many_dispatch
> await dispatch(result)
> File "D:\Najam\June\development\backend\Lib\site-packages\channels\consumer.py", line 73, in dispatch
> await handler(message)
> File "D:\Najam\June\development\backend\Lib\site-packages\channels\generic\websocket.py", line 194, in websocket_receive
> await self.receive(text_data=message["text"])
> File "D:\Najam\June\development\baba_drive_project_backend\app\rides\consumers.py", line 399, in receive
> await self.send_amount(text_data)
> File "D:\Najam\June\development\baba_drive_project_backend\app\rides\consumers.py", line 443, in send_amount
>     'data': f"{driver,location} {data['amount']}",
>             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
> File "D:\Najam\June\development\backend\Lib\site-packages\django\db\models\base.py", line 588, in __repr__
> return "<%s: %s>" % (self.__class__.__name__, self)
>                                                   ^^^^
> File "D:\Najam\June\development\baba_drive_project_backend\app\location\models.py", line 29, in __str__
> return f'{self.driver_id.name}'
>               ^^^^^^^^^^^^^^
> File "D:\Najam\June\development\backend\Lib\site-packages\django\db\models\fields\related_descriptors.py", line 236, in __get__
> rel_obj = self.get_object(instance)
>               ^^^^^^^^^^^^^^^^^^^^^^^^^
> File "D:\Najam\June\development\backend\Lib\site-packages\django\db\models\fields\related_descriptors.py", line 366, in get_object
> return super().get_object(instance)
>            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
> File "D:\Najam\June\development\backend\Lib\site-packages\django\db\models\fields\related_descriptors.py", line 199, in get_object
> return qs.get(self.field.get_reverse_related_filter(instance))
>            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
> File "D:\Najam\June\development\backend\Lib\site-packages\django\db\models\query.py", line 633, in get
> num = len(clone)
>           ^^^^^^^^^^
> File "D:\Najam\June\development\backend\Lib\site-packages\django\db\models\query.py", line 380, in __len__
> self._fetch_all()
> File "D:\Najam\June\development\backend\Lib\site-packages\django\db\models\query.py", line 1881, in _fetch_all
> self._result_cache = list(self._iterable_class(self))
>                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
> File "D:\Najam\June\development\backend\Lib\site-packages\django\db\models\query.py", line 91, in __iter__
> results = compiler.execute_sql(
>               ^^^^^^^^^^^^^^^^^^^^^
> File "D:\Najam\June\development\backend\Lib\site-packages\django\db\models\sql\compiler.py", line 1560, in execute_sql
> cursor = self.connection.cursor()
>              ^^^^^^^^^^^^^^^^^^^^^^^^
> File "D:\Najam\June\development\backend\Lib\site-packages\django\utils\asyncio.py", line 24, in inner
> raise SynchronousOnlyOperation(message)
> django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.

如果使用了该语句,则代码可以完美运行print()

python-3.x django-models 实时 django 通道

评论

0赞 CoffeeBasedLifeform 11/15/2023
请将错误回溯放在代码块而不是引号中 - 并避免添加您自己的格式(即 ^ 和 ~)。我试图编辑帖子,但回溯太糟糕了,所以我保持原样。
0赞 najam iqbal 11/16/2023
当然,谢谢!我会这样做的。
1赞 najam iqbal 11/16/2023
完成编辑后,请再次检查。@CoffeeBasedLifeform
1赞 9769953 11/16/2023
def **get_driver_location**(self,data)::尽量不要编辑带有 Markdown 标签或其他东西的代码:这现在是无效代码。还有其他更有效的方法来标记代码:使用相关代码上方或左侧(如果简短)的注释。
1赞 9769953 11/16/2023
注意:,靠近回溯跟踪的顶部。这可能是实际的错误。您的类没有字段。KeyError: 'driver_id'CabLocationdriver_id

答: 暂无答案