I am trying to login users in django channels and its throwing
AttributeError: 'AnonymousUser' object has no attribute '_meta'
My Consumer
class LoginConsumer(AsyncJsonWebsocketConsumer):
async def connect(self):
self.room_name = "login_room"
self.room_group_name = "login_group"
await self.channel_layer.group_add(self.room_group_name, self.channel_name)
await self.accept()
await self.send(json.dumps({"message": "connected to login socket"}))
async def receive(self, text_data):
self.json_data = json.loads(text_data)
await login(self.scope, await self.query())
await database_sync_to_async(self.scope["session"].save)()
async def query(self):
await self.get_user_from_db()
#database_sync_to_async
def get_user_from_db(self):
user = User.objects.get(username=self.json_data["username"])
return user
async def disconnect(self, code):
print("disconnected")
await super().disconnect(code)
My login view
def login_user(request):
if request.user.is_anonymous:
if request.method == "POST":
username = request.POST.get("username")
password = request.POST.get("password")
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return redirect("index")
else:
messages.error(request, "invalid username or password")
return redirect("login")
return render(request, "login.html")
else:
return redirect("index")
My js file
const username = document.querySelector(".username");
const password = document.querySelector(".password");
const socket = new WebSocket("ws://localhost:8000/ws/auth/login");
const button = document.querySelector("button");
button.addEventListener("click", (e) => {
if (password.value !== "" && username.value !== "") {
socket.send(
JSON.stringify({
username: username.value,
password: password.value,
})
);
}
});
Full Traceback:
Exception inside application: 'AnonymousUser' object has no attribute '_meta'
Traceback (most recent call last):
File "/home/__neeraj__/.local/lib/python3.9/site-packages/channels/staticfiles.py", line 44, in __call__
return await self.application(scope, receive, send)
File "/home/__neeraj__/.local/lib/python3.9/site-packages/channels/routing.py", line 71, in __call__
return await application(scope, receive, send)
File "/home/__neeraj__/.local/lib/python3.9/site-packages/channels/sessions.py", line 47, in __call__
return await self.inner(dict(scope, cookies=cookies), receive, send)
File "/home/__neeraj__/.local/lib/python3.9/site-packages/channels/sessions.py", line 263, in __call__
return await self.inner(wrapper.scope, receive, wrapper.send)
File "/home/__neeraj__/.local/lib/python3.9/site-packages/channels/auth.py", line 185, in __call__
return await super().__call__(scope, receive, send)
File "/home/__neeraj__/.local/lib/python3.9/site-packages/channels/middleware.py", line 26, in __call__
return await self.inner(scope, receive, send)
File "/home/__neeraj__/.local/lib/python3.9/site-packages/channels/routing.py", line 150, in __call__
return await application(
File "/home/__neeraj__/.local/lib/python3.9/site-packages/channels/consumer.py", line 94, in app
return await consumer(scope, receive, send)
File "/home/__neeraj__/.local/lib/python3.9/site-packages/channels/consumer.py", line 58, in __call__
await await_many_dispatch(
File "/home/__neeraj__/.local/lib/python3.9/site-packages/channels/utils.py", line 51, in await_many_dispatch
await dispatch(result)
File "/home/__neeraj__/.local/lib/python3.9/site-packages/channels/consumer.py", line 73, in dispatch
await handler(message)
File "/home/__neeraj__/.local/lib/python3.9/site-packages/channels/generic/websocket.py", line 194, in websocket_receive
await self.receive(text_data=message["text"])
File "/home/__neeraj__/Documents/chat/auth_user/consumers.py", line 20, in receive
await login(self.scope, await self.query())
File "/home/__neeraj__/.local/lib/python3.9/site-packages/asgiref/sync.py", line 444, in __call__
ret = await asyncio.wait_for(future, timeout=None)
File "/usr/lib/python3.9/asyncio/tasks.py", line 442, in wait_for
return await fut
File "/usr/lib/python3.9/concurrent/futures/thread.py", line 52, in run
result = self.fn(*self.args, **self.kwargs)
File "/home/__neeraj__/.local/lib/python3.9/site-packages/channels/db.py", line 13, in thread_handler
return super().thread_handler(loop, *args, **kwargs)
File "/home/__neeraj__/.local/lib/python3.9/site-packages/asgiref/sync.py", line 486, in thread_handler
return func(*args, **kwargs)
File "/home/__neeraj__/.local/lib/python3.9/site-packages/channels/auth.py", line 106, in login
session[SESSION_KEY] = user._meta.pk.value_to_string(user)
File "/home/__neeraj__/.local/lib/python3.9/site-packages/django/utils/functional.py", line 247, in inner
return func(self._wrapped, *args)
AttributeError: 'AnonymousUser' object has no attribute '_meta'
This error is occurring on the consumer not the view
Related
I'm building a basic websocket live chat using Django Channels and while the site loads fine, when I enter into the site, in my terminal I get this TypeError Message:
TypeError: Channel name must be a valid unicode string with length < 100 containing only ASCII alphanumerics, hyphens, underscores, or periods, not RedisChannelLayer(hosts=[{'host': '127.0.0.1', 'port': 6379}])
Im assuming the problem lies in my settings.py file but based on my current channel layer settings, I don't see what the problem is:
CHANNEL_LAYERS = {
'default': {
"BACKEND": 'channels_redis.core.RedisChannelLayer',
"CONFIG": {
"hosts": [('127.0.0.1', 6379)],
},
},
}
I'm new to django and channels so maybe there's a place where I defined the channel name and i'm just missing but I'm not sure or where to look for it if thats true.
This is my Full traceback error and consumer.py file btw:
Exception inside application: Channel name must be a valid unicode string with length < 100 containing only ASCII alphanumerics, hyphens, underscores, or periods, not RedisChannelLayer(hosts=[{'host': '127.0.0.1', 'port': 6379}])
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/contrib/staticfiles/handlers.py", line 101, in __call__
return await self.application(scope, receive, send)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/channels/routing.py", line 62, in __call__
return await application(scope, receive, send)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/channels/security/websocket.py", line 37, in __call__
return await self.application(scope, receive, send)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/channels/sessions.py", line 47, in __call__
return await self.inner(dict(scope, cookies=cookies), receive, send)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/channels/sessions.py", line 263, in __call__
return await self.inner(wrapper.scope, receive, wrapper.send)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/channels/auth.py", line 185, in __call__
return await super().__call__(scope, receive, send)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/channels/middleware.py", line 24, in __call__
return await self.inner(scope, receive, send)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/channels/routing.py", line 116, in __call__
return await application(
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/channels/consumer.py", line 94, in app
return await consumer(scope, receive, send)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/channels/consumer.py", line 58, in __call__
await await_many_dispatch(
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/channels/utils.py", line 50, in await_many_dispatch
await dispatch(result)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/channels/consumer.py", line 73, in dispatch
await handler(message)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/channels/generic/websocket.py", line 173, in websocket_connect
await self.connect()
File "/Users/alecsmith/Documents/Python Work/ChatApp/chat/consumers.py", line 10, in connect
await self.channel_layer.group_add(
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/channels_redis/core.py", line 518, in group_add
assert self.valid_channel_name(channel), "Channel name not valid"
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/channels/layers.py", line 160, in valid_channel_name
raise TypeError(self.invalid_name_error.format("Channel", name))
TypeError: Channel name must be a valid unicode string with length < 100 containing only ASCII alphanumerics, hyphens, underscores, or periods, not RedisChannelLayer(hosts=[{'host': '127.0.0.1', 'port': 6379}])
import json
from channels.generic.websocket import AsyncWebsocketConsumer
# Class tells websocket how it should be used when doing real time events betweeen computer and server
class ChatConsumer(AsyncWebsocketConsumer):
# Accepts the connection of the websocket, makes a group name for the chatroom,
# and add the group to the channel layer
async def connect(self):
self.roomGroupName = 'group_chat_gfg'
await self.channel_layer.group_add(
self.roomGroupName,
self.channel_layer
)
await self.accept()
# Removes the group name and removes the group itself from the channel layer
async def disconnect(self):
await self.channel_layer.group_discard(
self.roomGroupName,
self.channel_layer
)
# Recieves the message and spreads it to all other users in the chat room
async def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['message']
username = text_data_json['username']
await self.channel_layer.group_send(
self.roomGroupName, {
'type': 'sendMessage',
'message': message,
'username': username
}
)
# Takes the name of the user and their message and sends it to the chat room
async def sendMessage(self, event):
message = event['message']
username = event['username']
await self.send(text_data = json.dumps({'message': message, 'username': username}))
You should pass self.channel_name to group_add() and not self.channel_layer
async def connect(self):
self.roomGroupName = 'group_chat_gfg'
await self.channel_layer.group_add(
self.roomGroupName,
self.channel_name # here
)
await self.accept()
async def disconnect(self):
await self.channel_layer.group_discard(
self.roomGroupName,
self.channel_name # and here
)
I am new to python and fastapi, and was playing around it.
I wrote this code
from fastapi import FastAPI
app = FastAPI()
people = {
"1": {
"name": "abc",
"age": 27
},
"2": {
"name": "xyz",
"age": 60
}
}
#app.get("/")
def read_root():
return {"Hello": "World"}
#app.get("/people/")
def get_people(
min_age: int=0, max_age: int=100
):
results = [person for person in people.values() if person["age"] >= min_age and person["age"] <= max_age]
return results
#app.get("/people/{person_id}")
def get_person(person_id: int):
return people[person_id]
but on calling #app.get("/people/{person_id}") I am getting 500 error with this as traceback
Traceback (most recent call last):
File "/Users/abcB/Desktop/fastapi-tutorial/env/lib/python3.9/site-packages/uvicorn/protocols/http/h11_impl.py", line 407, in run_asgi
result = await app( # type: ignore[func-returns-value]
File "/Users/abcB/Desktop/fastapi-tutorial/env/lib/python3.9/site-packages/uvicorn/middleware/proxy_headers.py", line 78, in __call__
return await self.app(scope, receive, send)
File "/Users/abcB/Desktop/fastapi-tutorial/env/lib/python3.9/site-packages/fastapi/applications.py", line 270, in __call__
await super().__call__(scope, receive, send)
File "/Users/abcB/Desktop/fastapi-tutorial/env/lib/python3.9/site-packages/starlette/applications.py", line 124, in __call__
await self.middleware_stack(scope, receive, send)
File "/Users/abcB/Desktop/fastapi-tutorial/env/lib/python3.9/site-packages/starlette/middleware/errors.py", line 184, in __call__
raise exc
File "/Users/abcB/Desktop/fastapi-tutorial/env/lib/python3.9/site-packages/starlette/middleware/errors.py", line 162, in __call__
await self.app(scope, receive, _send)
File "/Users/abcB/Desktop/fastapi-tutorial/env/lib/python3.9/site-packages/starlette/middleware/exceptions.py", line 79, in __call__
raise exc
File "/Users/abcB/Desktop/fastapi-tutorial/env/lib/python3.9/site-packages/starlette/middleware/exceptions.py", line 68, in __call__
await self.app(scope, receive, sender)
File "/Users/abcB/Desktop/fastapi-tutorial/env/lib/python3.9/site-packages/fastapi/middleware/asyncexitstack.py", line 21, in __call__
raise e
File "/Users/abcB/Desktop/fastapi-tutorial/env/lib/python3.9/site-packages/fastapi/middleware/asyncexitstack.py", line 18, in __call__
await self.app(scope, receive, send)
File "/Users/abcB/Desktop/fastapi-tutorial/env/lib/python3.9/site-packages/starlette/routing.py", line 706, in __call__
await route.handle(scope, receive, send)
File "/Users/abcB/Desktop/fastapi-tutorial/env/lib/python3.9/site-packages/starlette/routing.py", line 276, in handle
await self.app(scope, receive, send)
File "/Users/abcB/Desktop/fastapi-tutorial/env/lib/python3.9/site-packages/starlette/routing.py", line 66, in app
response = await func(request)
File "/Users/abcB/Desktop/fastapi-tutorial/env/lib/python3.9/site-packages/fastapi/routing.py", line 235, in app
raw_response = await run_endpoint_function(
File "/Users/abcB/Desktop/fastapi-tutorial/env/lib/python3.9/site-packages/fastapi/routing.py", line 163, in run_endpoint_function
return await run_in_threadpool(dependant.call, **values)
File "/Users/abcB/Desktop/fastapi-tutorial/env/lib/python3.9/site-packages/starlette/concurrency.py", line 41, in run_in_threadpool
return await anyio.to_thread.run_sync(func, *args)
File "/Users/abcB/Desktop/fastapi-tutorial/env/lib/python3.9/site-packages/anyio/to_thread.py", line 31, in run_sync
return await get_asynclib().run_sync_in_worker_thread(
File "/Users/abcB/Desktop/fastapi-tutorial/env/lib/python3.9/site-packages/anyio/_backends/_asyncio.py", line 937, in run_sync_in_worker_thread
return await future
File "/Users/abcB/Desktop/fastapi-tutorial/env/lib/python3.9/site-packages/anyio/_backends/_asyncio.py", line 867, in run
result = context.run(func, *args)
File "/Users/abcB/Desktop/fastapi-tutorial/./main.py", line 31, in get_person
return people[person_id]
Can someone point me on what I am doing wrong here?
In your dictionary "people" you have declared the "id" (the keys) as strings.
However in the path operation of #app.get("/people/{person_id}") you have declared the person_id as an int. That's why the error occurs. Remember that pydantic uses these type declarations for data validation.
The correct thing would then be:
#app.get("/people/{person_id}")
def get_person(person_id: str):
return people[person_id]
I'm observing closedResourceError when sending multiple requests using httpx async client. httpx version used is 0.19.0. Has anyone faced similar issue? if it is an issue and fixed in later version?
Logs:
resp = await asyncio.gather(*[self.async_send_request(method,self.dest_host,self.dest_port,uri,i,payload=payload,headers=headers) for i in range(int(times) )])
File "/env/lib64/python3.9/site-packages/ocnftest_lib/scp_Pcf_client.py", line 175, in async_send_request
return await self.conn.request(method,"http://{}:{}{}".format(self.dest_host,self.dest_port,uri),data=payload,headers=headers,allow_redirects=False)
File "/env/lib64/python3.9/site-packages/httpx/_client.py", line 1494, in request
response = await self.send(
File "/env/lib64/python3.9/site-packages/httpx/_client.py", line 1586, in send
response = await self._send_handling_auth(
File "/env/lib64/python3.9/site-packages/httpx/_client.py", line 1616, in _send_handling_auth
response = await self._send_handling_redirects(
File "/env/lib64/python3.9/site-packages/httpx/_client.py", line 1655, in _send_handling_redirects
response = await self._send_single_request(request, timeout)
File "/env/lib64/python3.9/site-packages/httpx/_client.py", line 1699, in _send_single_request
) = await transport.handle_async_request(
File "/env/lib64/python3.9/site-packages/httpx/_transports/default.py", line 281, in handle_async_request
) = await self._pool.handle_async_request(
File "/env/lib64/python3.9/site-packages/httpcore/_async/connection_pool.py", line 234, in handle_async_request
response = await connection.handle_async_request(
File "/env/lib64/python3.9/site-packages/httpcore/_async/connection.py", line 148, in handle_async_request
return await self.connection.handle_async_request(
File "/env/lib64/python3.9/site-packages/httpcore/_async/http2.py", line 165, in handle_async_request
return await h2_stream.handle_async_request(
File "/env/lib64/python3.9/site-packages/httpcore/_async/http2.py", line 339, in handle_async_request
await self.send_headers(method, url, headers, has_body, timeout)
File "/env/lib64/python3.9/site-packages/httpcore/_async/http2.py", line 398, in send_headers
await self.connection.send_headers(self.stream_id, headers, end_stream, timeout)
File "/env/lib64/python3.9/site-packages/httpcore/_async/http2.py", line 274, in send_headers
await self.socket.write(data_to_send, timeout)
File "/env/lib64/python3.9/site-packages/httpcore/_backends/anyio.py", line 77, in write
return await self.stream.send(data)
File "/env/lib64/python3.9/site-packages/anyio/_backends/_asyncio.py", line 1116, in send
raise ClosedResourceError
anyio.ClosedResourceError
Sample Code
async def send_request(self,payload,times,method,uri,headers):
resp = await asyncio.gather(*[self.async_send_request(method,self.dest_host,self.dest_port,uri,i,payload=payload,headers=headers) for i in range(int(times) )])
await self.conn.aclose()
log.logger.info("[+] #{} {} {}".format(method,resp[int(times)-1].status_code,uri))
return resp[int(times)-1]
async def async_send_request(self,method,dest_host,dest_port,uri,times,payload=None,headers=None):
if self.security == 'secure':
return await self.conn.request(method,"https://{}:{}{}".format(self.dest_host,self.dest_port,uri),data=payload,headers=headers,allow_redirects=False)
else:
return await self.conn.request(method,"http://{}:{}{}".format(self.dest_host,self.dest_port,uri),data=payload,headers=headers,allow_redirects=False)
def send_message:
self.conn = httpx.AsyncClient(http2=True,http1=False,proxies=self.proxies,timeout=10)
response = asyncio.run(self.send_request(payload,times,method,uri,headers))
I am new to FastAPI and I am stuck at fastapi's put method. I am following a certain tutorial.
Here is the code:
#app.put("/blog/{blog_id}", status_code=status.HTTP_202_ACCEPTED)
def update(blog_id: int, request: schemas.Blog,
db: Session = Depends(get_db)):
blog = db.query(models.Blog).filter(models.Blog.id == blog_id)
if blog.first() is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
detail="Blog not found")
blog.update(request, synchronize_session=False)
db.commit()
return 'Blog updated'
#app.patch("/blog/{blog_id}", status_code=status.HTTP_202_ACCEPTED)
def partial_update(blog_id: int, request: schemas.Blog,
db: Session = Depends(get_db)):
blog = db.query(models.Blog).filter(models.Blog.id == blog_id)
if blog.first() is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
detail="Blog not found")
blog.update(request, synchronize_session=False)
db.commit()
return 'Blog updated'
but the thing it is not updating the contents and is giving error 500 if I try to update it.
In console following error is shown:
File "/home/satvir/Documents/dev/FastApi_Tutorial/.env/lib/python3.9/site-packages/starlette/middleware/errors.py", line 159, in __call__
await self.app(scope, receive, _send)
File "/home/satvir/Documents/dev/FastApi_Tutorial/.env/lib/python3.9/site-packages/starlette/exceptions.py", line 82, in __call__
raise exc from None
File "/home/satvir/Documents/dev/FastApi_Tutorial/.env/lib/python3.9/site-packages/starlette/exceptions.py", line 71, in __call__
await self.app(scope, receive, sender)
File "/home/satvir/Documents/dev/FastApi_Tutorial/.env/lib/python3.9/site-packages/starlette/routing.py", line 566, in __call__
await route.handle(scope, receive, send)
File "/home/satvir/Documents/dev/FastApi_Tutorial/.env/lib/python3.9/site-packages/starlette/routing.py", line 227, in handle
await self.app(scope, receive, send)
File "/home/satvir/Documents/dev/FastApi_Tutorial/.env/lib/python3.9/site-packages/starlette/routing.py", line 41, in app
response = await func(request)
File "/home/satvir/Documents/dev/FastApi_Tutorial/.env/lib/python3.9/site-packages/fastapi/routing.py", line 201, in app
raw_response = await run_endpoint_function(
File "/home/satvir/Documents/dev/FastApi_Tutorial/.env/lib/python3.9/site-packages/fastapi/routing.py", line 150, in run_endpoint_function
return await run_in_threadpool(dependant.call, **values)
File "/home/satvir/Documents/dev/FastApi_Tutorial/.env/lib/python3.9/site-packages/starlette/concurrency.py", line 34, in run_in_threadpool
return await loop.run_in_executor(None, func, *args)
File "/usr/lib/python3.9/concurrent/futures/thread.py", line 52, in run
result = self.fn(*self.args, **self.kwargs)
File "/home/satvir/Documents/dev/FastApi_Tutorial/./Blog/main.py", line 64, in update
blog.update(request, synchronize_session=False)
File "/home/satvir/Documents/dev/FastApi_Tutorial/.env/lib/python3.9/site-packages/sqlalchemy/orm/query.py", line 3204, in update
upd = upd.values(values)
File "<string>", line 2, in values
File "/home/satvir/Documents/dev/FastApi_Tutorial/.env/lib/python3.9/site-packages/sqlalchemy/sql/base.py", line 106, in _generative
x = fn(self, *args, **kw)
File "<string>", line 2, in values
File "/home/satvir/Documents/dev/FastApi_Tutorial/.env/lib/python3.9/site-packages/sqlalchemy/sql/base.py", line 135, in check
return fn(self, *args, **kw)
File "/home/satvir/Documents/dev/FastApi_Tutorial/.env/lib/python3.9/site-packages/sqlalchemy/sql/dml.py", line 701, in values
for k, v in arg.items()
AttributeError: 'Blog' object has no attribute 'items'
schemas.Blog:
class Blog(BaseModel):
title: str
content: str
models.Blog:
class Blog(Base):
__tablename__ = "blogs"
id = Column(Integer, primary_key=True, index=True)
title = Column(String)
description = Column(String)
Everything else: creating, retrieving, deleting methods are working fine.
Please help me what to do??
The solution is to change blog.update(request, synchronize_session=False) in your update function to :
blog.update(request.__dict__, synchronize_session=False)
I'll explain why.
From the error message provided, sqlalchemy is attempting to loop over a dictionary, hence it gives that error message when it cannot find a dict type.
The request parameter in blog.update() method is of type Class. To confirm, add this line of code after your if statement:
print(type(request))
You should get an output similar to:
<class 'blog.schemas.Blog'>
Hence, the error. Now do this: print(type(request.__dict__)). Your output should be similar to this: <class 'dict'> which solves the problem.
I wish to make simple program in django channels - I open Websocket and then listen for users clicking a button or pressing any key down. If such event occurs JS sends message to Channels where it gets access to db where there is a model of a counter, increment it depends it was click or key, and then send it back to group on layers. Unfortunately, error occurs. Why does it call context error if I already used database_sync_to_async?
My 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()
Error:
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.
You should be calling the database_sync_to_async method, and not the save method directly:
async def receive(self, text_data):
...
await database_sync_to_async(self.counter.save)()
...