Skip to content

Allow Django ORM usage within components #80

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 9 commits into from
Closed
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ Types of changes are to be listed in this order

## [Unreleased]

- Nothing (yet)
### Fixed

- Django ORM can now be directly called within components without causing a `SynchronousOnlyOperation` exception.

## [1.0.0] - 2022-05-22

Expand Down
2 changes: 1 addition & 1 deletion requirements/test-env.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
django
selenium
selenium <= 4.2.0
twisted
27 changes: 27 additions & 0 deletions src/django_idom/layout.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import os

from idom.core.layout import Layout, LayoutUpdate


class DjangoLayout(Layout):
"""Fixes Django ORM usage within components.
These issues are caused by async/sync mixed context limitations in the ORM.
Without this, `SynchronousOnlyOperation` exceptions occur when using the ORM in IDOM components.
This may be fixed in a future version, such as Django 5.0."""

def _create_layout_update(self, old_state) -> LayoutUpdate:
"""Create a layout update, but set ALLOW ASYNC UNSAFE flags prior.
This allows the Django ORM to be used within components."""
async_unsafe_prev = os.environ.get("DJANGO_ALLOW_ASYNC_UNSAFE", None)

# Set ALLOW ASYNC UNSAFE to True
os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true"
layout_update = super()._create_layout_update(old_state)

# Reset async unsafe flag to the previous value
if async_unsafe_prev is not None:
os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = async_unsafe_prev
else:
os.environ.pop("DJANGO_ALLOW_ASYNC_UNSAFE")

return layout_update
5 changes: 3 additions & 2 deletions src/django_idom/websocket/consumer.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@
from channels.auth import login
from channels.db import database_sync_to_async as convert_to_async
from channels.generic.websocket import AsyncJsonWebsocketConsumer
from idom.core.layout import Layout, LayoutEvent
from idom.core.layout import LayoutEvent
from idom.core.serve import serve_json_patch

from django_idom.config import IDOM_REGISTERED_COMPONENTS
from django_idom.hooks import IdomWebsocket, WebsocketContext
from django_idom.layout import DjangoLayout


_logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -73,7 +74,7 @@ async def _run_dispatch_loop(self):
self._idom_recv_queue = recv_queue = asyncio.Queue()
try:
await serve_json_patch(
Layout(WebsocketContext(component_instance, value=socket)),
DjangoLayout(WebsocketContext(component_instance, value=socket)),
self.send_json,
recv_queue.get,
)
Expand Down
18 changes: 18 additions & 0 deletions tests/test_app/components.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from uuid import uuid4

import idom

import django_idom
Expand Down Expand Up @@ -71,3 +73,19 @@ def UseLocation():
f"UseLocation: {location}",
idom.html.hr(),
)


@idom.component
def OrmInComponent():
from .models import NamedThingy

NamedThingy.objects.all().delete()
NamedThingy(name=f"foo-{uuid4()}").save()
model = NamedThingy.objects.all()
success = bool(model)

return idom.html.div(
{"id": "orm-in-component", "data-success": success},
f"OrmInComponent: {model}",
idom.html.hr(),
)
28 changes: 28 additions & 0 deletions tests/test_app/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Generated by Django 4.0.5 on 2022-06-26 02:24

from django.db import migrations, models


class Migration(migrations.Migration):

initial = True

dependencies = []

operations = [
migrations.CreateModel(
name="NamedThingy",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("name", models.CharField(max_length=255)),
],
),
]
8 changes: 8 additions & 0 deletions tests/test_app/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from django.db import models


class NamedThingy(models.Model):
def __str__(self):
return self.name

name = models.CharField(max_length=255)
4 changes: 3 additions & 1 deletion tests/test_app/templates/base.html
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{% load static %} {% load idom %}
{% load static %} {% load idom %} {% load idom_tests %}
<!DOCTYPE html>
<html lang="en">

Expand All @@ -19,6 +19,8 @@ <h1>IDOM Test Page</h1>
<div>{% component "test_app.components.UseWebsocket" %}</div>
<div>{% component "test_app.components.UseScope" %}</div>
<div>{% component "test_app.components.UseLocation" %}</div>
<div>{% component "test_app.components.OrmInComponent" %}</div>
<div id="allow-async-unsafe" data-value="{% check_async_unsafe %}">DJANGO_ALLOW_ASYNC_UNSAFE: {% check_async_unsafe %}<hr></div>
</body>

</html>
Empty file.
11 changes: 11 additions & 0 deletions tests/test_app/templatetags/idom_tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import os

from django import template


register = template.Library()


@register.simple_tag
def check_async_unsafe():
return bool(os.environ.get("DJANGO_ALLOW_ASYNC_UNSAFE", None))
8 changes: 8 additions & 0 deletions tests/test_app/tests/test_components.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,14 @@ def test_use_location(self):
element = self.driver.find_element_by_id("use-location")
self.assertEqual(element.get_attribute("data-success"), "true")

def test_orm_in_component(self):
element = self.driver.find_element_by_id("orm-in-component")
self.assertEqual(element.get_attribute("data-success"), "true")

# Make sure ASYNC_UNSAFE value was reset after component render
element = self.driver.find_element_by_id("allow-async-unsafe")
self.assertEqual(element.get_attribute("data-value"), "False")


def make_driver(page_load_timeout, implicit_wait_timeout):
options = webdriver.ChromeOptions()
Expand Down