Ah yes, that's because the URL parsing/conversion all happens in the main 
(async, in ASGI mode) thread - and because to_python is a a synchronous 
function interface, there is literally nothing you can do to make it work.

The only real way of fixing this would be for Django to patch the URL 
converters and run them all in a synchronous mode unless they were decorated as 
"safe" somehow, much like we do for middleware. It's not a terribly hard patch 
to make, but it does mean you don't have an immediate solution. There are ways 
of trying to work around it, but they will all result in you blocking the async 
thread while the ORM query runs, which would be disastrous in production.

My apologies for not getting this in for the original async view patch - I had 
forgotten converters ran in the URL resolver.

Andrew

On Sat, Jun 19, 2021, at 12:31 AM, konstanti...@gmail.com 
<mailto:konstanti...%40gmail.com> wrote:
> 
> I'm trying to switch from WSGI to ASGI and I'm having issues with my model id 
> to model converters.
> I define my converters like this
> def to_python(self, primary_key):
>      try:
>           return self.model.objects.get(pk=primary_key)
>      except self.model.DoesNotExist:
>           raise ValueError
> When I go to a url where a converter is used I get a SynchronousOnlyOperation.
> Seems like converters are executed in an async context.
> If I use sync_to_async, I get a coroutine in my view instead of a model 
> instance. Awaiting it here would defeat the purpose of having a converter.
> 
> Any ideas how to fix this?
> 

> -- 
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an 
> email to django-users+unsubscr...@googlegroups.com.
> To view this discussion on the web visit 
> https://groups.google.com/d/msgid/django-users/ef60ed71-7f4f-482d-b540-bdf89e249aa4n%40googlegroups.com
>  
> <https://groups.google.com/d/msgid/django-users/ef60ed71-7f4f-482d-b540-bdf89e249aa4n%40googlegroups.com?utm_medium=email&utm_source=footer>.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/34c22d74-ba14-45b0-81fa-85f03c5f34af%40www.fastmail.com.

Reply via email to