Skip to content

check_request_enabled.send() should not be called from an async context #915

@Ariki

Description

@Ariki

Understanding CORS

  • I have read the resources.

Python Version

3.11

Django Version

4.2

Package Version

4.3.1

Description

The current CorsMiddleware implementation can work both in sync and async mode. The issue is that even in async mode, it uses Django signal's send method which isn't intended to be used from an async context.

This kind of works in simple cases but you cannot use Django ORM functions from a signal handler called in an asynchronous context.

Starting from version 5.0, Django supports asynchronous signal handlers and introduces the asend method which can be used to send signals from asynchronous code.

So I believe the correct approach would be as follows:

  • use send if the middleware is run in synchronous mode;
  • wrap send to sync_to_async() if the middleware is run in asynchronous mode, and Django version is < 5.0;
  • use asend if the middleware is run in asynchronous mode, and Django version is >=5.0.

Some refactoring is needed for this to work, as await can be used only in async methods.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions