Answer the question
In order to leave comments, you need to log in
I can't understand asynchrony in Django, what and where to read?
I welcome everyone! Learned Python as my first language and Django as my first framework. Having studied the basics from Dronov's book, I managed to make several projects, but at the moment I wanted to make a chat, which requires asynchrony. However, after reading a considerable number of articles, both in Russian-speaking and in English-speaking spaces of the Internet, where either the very tops are given or they are removed into the wilds. What good articles and/or videos can you recommend for the concept of asynchrony?
I tried to write my code with the chat as simple as possible, could you clarify what is wrong here?
@sync_to_async
def testchat(request):
get_message = sync_to_async(Message.objects.all())
message = get_message()
if request.method == 'POST':
msf = MessageForm(request.POST)
if msf.is_valid():
msf.save()
return HttpResponseRedirect(reverse('main:testchat', args=()))
else:
context = {'form' : msf, 'message' : message}
return render(request, 'main/testchat.html', context)
else:
msf = MessageForm(request.POST)
context = {'form' : msf, 'message' : message}
return render(request, 'main/testchat.html', context)
#Сделал два варианта гов... кхм, кода.
async def testchat(request):
message = await sync_to_async(Message.objects.all(), thread_sensitive=True)
if request.method == 'POST':
msf = await sync_to_async(MessageForm(request.POST), thread_sensitive=True)
if msf.is_valid():
msf.save()
return HttpResponseRedirect(reverse('main:testchat', args=()))
else:
context = {'form' : msf}
return render(request, 'main/testchat.html', context)
else:
msf = await sync_to_async(MessageForm(request.POST), thread_sensitive=True)
context = {'form' : msf}
Answer the question
In order to leave comments, you need to log in
Asynchrony has been recently introduced in django, and it is not in all parts. Well, using it for training is a very bad idea.
PS Asynchrony is needed for websocket-based chats, channels are usually used for this, but I really don’t like it (this is my subjective opinion), I usually raise the chat via aiohttp next to it.
PS2 also googled the current state, people are still trying to write an implementation themselves, if you do not use channels, https://alex-oleshkevich.medium.com/websockets-in-...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question