Skip to content

Async Compatibility #68

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

Open
BrandonShar opened this issue Feb 5, 2025 · 1 comment
Open

Async Compatibility #68

BrandonShar opened this issue Feb 5, 2025 · 1 comment

Comments

@BrandonShar
Copy link
Collaborator

Creating this to track issues and progress of making Inertia Django async compatible. I was able to proof of concept this, but I had to go outside of the inertia syntax a few times on both the front and backend.

@engAmirEng
Copy link

engAmirEng commented Mar 24, 2025

i did not find it troubling, if you desire to use @inertia, then just do this:

from asgiref.sync import sync_to_async

def inertia(component, layout):
    def decorator(func):
        if asyncio.iscoroutinefunction(func):
            @wraps(func)
            async def inner(request, *args, **kwargs):
                props = await func(request, *args, **kwargs)
                if not isinstance(props, dict):
                    return props

                return await sync_to_async(render)(request, inertia_layout=layout, component=component, props=props)
        else:
            @wraps(func)
            def inner(request, *args, **kwargs):
                props = func(request, *args, **kwargs)
                if not isinstance(props, dict):
                    return props

                return render(request, inertia_layout=layout, component=component, props=props)

        return inner

    return decorator

@inertia('Event/Index')
async def index(request):
  return {
    'events': Event.objects.all(),
  }

this pattern of modifying the decorator in a way that works both with sync and async views is used in the django source itself
and no need to modify and change any js what so ever

and if you want to use the render directly then:

from asgiref.sync import sync_to_async

async def index(request):
  return sync_to_async(render)(request, 'Event/Index', props={
    'events': Event.objects.all()
  })

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants