gpt4 book ai didi

python - 使用 django channel 保存数据库更改

转载 作者:行者123 更新时间:2023-12-02 19:08:46 25 4
gpt4 key购买 nike

我希望在 django channel 中制作简单的程序 - 我打开 Websocket,然后监听用户单击按钮或按下任意键。如果发生此类事件,JS 会向 Channels 发送消息,在 Channels 中它可以访问有计数器模型的 db,根据单击或按键来递增它,然后将其发送回层上的组。不幸的是,发生了错误。如果我已经使用了database_sync_to_async,为什么它会调用上下文错误?

我的consumers.py:

from channels.generic.websocket import AsyncWebsocketConsumer
import json
from channels.db import database_sync_to_async
from .models import Licznik

class MyConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.room_group_name = 'main_room'
self.counter = await database_sync_to_async(self.get_counter)()

await (self.channel_layer.group_add)(
self.room_group_name,
self.channel_name
)
await self.accept()


def get_counter(self):
return Licznik.objects.all()[0]

async def receive(self, text_data):
if text_data == "klik":
self.counter.klik +=1
elif text_data == "klak":
self.counter.key += 1
await database_sync_to_async(self.counter.save()) #error here
klik = self.counter.klik
klak = self.counter.key
await (self.channel_layer.group_send)(
self.room_group_name,
{
'type': 'chat_message',
'klik': klik,
'klak': klak
}
)

async def chat_message(self, event):
message_klik = event['klik']
message_klak = event['klak']
await self.send(text_data=json.dumps({
'klik': message_klik,
'klak': message_klak
}))

async def disconnect(self, close_code):
await (self.channel_layer.group_discard)(
self.room_group_name,
self.channel_name
)
await self.close()

错误:

Exception inside application: You cannot call this from an async context - use a thread or sync_to_async.
Traceback (most recent call last):
File "/Users/dottore/PycharmProjects/klikator/venv/lib/python3.8/site-packages/channels/sessions.py", line 183, in __call__
return await self.inner(receive, self.send)
File "/Users/dottore/PycharmProjects/klikator/venv/lib/python3.8/site-packages/channels/middleware.py", line 41, in coroutine_call
await inner_instance(receive, send)
File "/Users/dottore/PycharmProjects/klikator/venv/lib/python3.8/site-packages/channels/consumer.py", line 58, in __call__
await await_many_dispatch(
File "/Users/dottore/PycharmProjects/klikator/venv/lib/python3.8/site-packages/channels/utils.py", line 51, in await_many_dispatch
await dispatch(result)
File "/Users/dottore/PycharmProjects/klikator/venv/lib/python3.8/site-packages/channels/consumer.py", line 73, in dispatch
await handler(message)
File "/Users/dottore/PycharmProjects/klikator/venv/lib/python3.8/site-packages/channels/generic/websocket.py", line 196, in websocket_receive
await self.receive(text_data=message["text"])
File "/Users/dottore/PycharmProjects/klikator/klikator/klikacz/consumers.py", line 26, in receive
await database_sync_to_async(self.counter.save())
File "/Users/dottore/PycharmProjects/klikator/venv/lib/python3.8/site-packages/django/db/models/base.py", line 753, in save
self.save_base(using=using, force_insert=force_insert,
File "/Users/dottore/PycharmProjects/klikator/venv/lib/python3.8/site-packages/django/db/models/base.py", line 790, in save_base
updated = self._save_table(
File "/Users/dottore/PycharmProjects/klikator/venv/lib/python3.8/site-packages/django/db/models/base.py", line 872, in _save_table
updated = self._do_update(base_qs, using, pk_val, values, update_fields,
File "/Users/dottore/PycharmProjects/klikator/venv/lib/python3.8/site-packages/django/db/models/base.py", line 926, in _do_update
return filtered._update(values) > 0
File "/Users/dottore/PycharmProjects/klikator/venv/lib/python3.8/site-packages/django/db/models/query.py", line 803, in _update
return query.get_compiler(self.db).execute_sql(CURSOR)
File "/Users/dottore/PycharmProjects/klikator/venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1522, in execute_sql
cursor = super().execute_sql(result_type)
File "/Users/dottore/PycharmProjects/klikator/venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1154, in execute_sql
cursor = self.connection.cursor()
File "/Users/dottore/PycharmProjects/klikator/venv/lib/python3.8/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.

最佳答案

您应该调用 database_sync_to_async方法,而不是直接保存方法:

async def receive(self, text_data):
...
await database_sync_to_async<b>(self.counter.save)()</b>
...

关于python - 使用 django channel 保存数据库更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64654537/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com