Closed
Description
I'm currently converting some puppeteer code to playright-python. And I'm taking this opportunity to use my django models rather than raw SQL queries:
#!/usr/bin/env python3
import os, sys
import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
django.setup()
from playwright import sync_playwright
from models import SomeModelClass
with sync_playwright() as playwright:
objs = SomeModelClass.objects.filter(pk=1)
print(objs)
However, I'm running into some issues and I would appreciate some guidance:
- I started by using the sync API, but when I try to run a query like:
SomeModelClass.objects.get(pk=1)
, I get the following error:django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.
- I then tried to use
sync_to_async
, from https://docs.djangoproject.com/en/3.1/topics/async/#asgiref.sync.sync_to_async. But this leads to further errors. - I then converted by entire code to use the async API, but this did not quite solve the issue, since django querysets are evaluated lazyly, i.e. outside the (in this case) async method.
- I did build upon 3. and forced the queryset to be evaluated inside the async method:
@sync_to_async
def getData():
objs= SomeModelClass.objects.filter(pk=1)
return list(objs)
This seemed to work, but at the expense of code complexity and I starting running into timeout issues.
- The only solution that's been easy to use was as follows:
os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true"
But, as pointed out by django, it may result in data loss.
Any advice from the team?