Sunday, June 20, 2021

Re: register_converter doesn't work with ASGI

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 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+unsubscribe@googlegroups.com.

No comments:

Post a Comment