ASGI specification and utilities

Related tags

WSGI Serversasgiref
Overview

asgiref

ASGI is a standard for Python asynchronous web apps and servers to communicate with each other, and positioned as an asynchronous successor to WSGI. You can read more at https://asgi.readthedocs.io/en/latest/

This package includes ASGI base libraries, such as:

  • Sync-to-async and async-to-sync function wrappers, asgiref.sync
  • Server base classes, asgiref.server
  • A WSGI-to-ASGI adapter, in asgiref.wsgi

Function wrappers

These allow you to wrap or decorate async or sync functions to call them from the other style (so you can call async functions from a synchronous thread, or vice-versa).

In particular:

  • AsyncToSync lets a synchronous subthread stop and wait while the async function is called on the main thread's event loop, and then control is returned to the thread when the async function is finished.
  • SyncToAsync lets async code call a synchronous function, which is run in a threadpool and control returned to the async coroutine when the synchronous function completes.

The idea is to make it easier to call synchronous APIs from async code and asynchronous APIs from synchronous code so it's easier to transition code from one style to the other. In the case of Channels, we wrap the (synchronous) Django view system with SyncToAsync to allow it to run inside the (asynchronous) ASGI server.

Note that exactly what threads things run in is very specific, and aimed to keep maximum compatibility with old synchronous code. See "Synchronous code & Threads" below for a full explanation. By default, sync_to_async will run all synchronous code in the program in the same thread for safety reasons; you can disable this for more performance with @sync_to_async(thread_sensitive=False), but make sure that your code does not rely on anything bound to threads (like database connections) when you do.

Threadlocal replacement

This is a drop-in replacement for threading.local that works with both threads and asyncio Tasks. Even better, it will proxy values through from a task-local context to a thread-local context when you use sync_to_async to run things in a threadpool, and vice-versa for async_to_sync.

If you instead want true thread- and task-safety, you can set thread_critical on the Local object to ensure this instead.

Server base classes

Includes a StatelessServer class which provides all the hard work of writing a stateless server (as in, does not handle direct incoming sockets but instead consumes external streams or sockets to work out what is happening).

An example of such a server would be a chatbot server that connects out to a central chat server and provides a "connection scope" per user chatting to it. There's only one actual connection, but the server has to separate things into several scopes for easier writing of the code.

You can see an example of this being used in frequensgi.

WSGI-to-ASGI adapter

Allows you to wrap a WSGI application so it appears as a valid ASGI application.

Simply wrap it around your WSGI application like so:

asgi_application = WsgiToAsgi(wsgi_application)

The WSGI application will be run in a synchronous threadpool, and the wrapped ASGI application will be one that accepts http class messages.

Please note that not all extended features of WSGI may be supported (such as file handles for incoming POST bodies).

Dependencies

asgiref requires Python 3.6 or higher.

Contributing

Please refer to the main Channels contributing docs.

Testing

To run tests, make sure you have installed the tests extra with the package:

cd asgiref/
pip install -e .[tests]
pytest

Building the documentation

The documentation uses Sphinx:

cd asgiref/docs/
pip install sphinx

To build the docs, you can use the default tools:

sphinx-build -b html . _build/html  # or `make html`, if you've got make set up
cd _build/html
python -m http.server

...or you can use sphinx-autobuild to run a server and rebuild/reload your documentation changes automatically:

pip install sphinx-autobuild
sphinx-autobuild . _build/html

Implementation Details

Synchronous code & threads

The asgiref.sync module provides two wrappers that let you go between asynchronous and synchronous code at will, while taking care of the rough edges for you.

Unfortunately, the rough edges are numerous, and the code has to work especially hard to keep things in the same thread as much as possible. Notably, the restrictions we are working with are:

  • All synchronous code called through SyncToAsync and marked with thread_sensitive should run in the same thread as each other (and if the outer layer of the program is synchronous, the main thread)
  • If a thread already has a running async loop, AsyncToSync can't run things on that loop if it's blocked on synchronous code that is above you in the call stack.

The first compromise you get to might be that thread_sensitive code should just run in the same thread and not spawn in a sub-thread, fulfilling the first restriction, but that immediately runs you into the second restriction.

The only real solution is to essentially have a variant of ThreadPoolExecutor that executes any thread_sensitive code on the outermost synchronous thread - either the main thread, or a single spawned subthread.

This means you now have two basic states:

  • If the outermost layer of your program is synchronous, then all async code run through AsyncToSync will run in a per-call event loop in arbitrary sub-threads, while all thread_sensitive code will run in the main thread.
  • If the outermost layer of your program is asynchronous, then all async code runs on the main thread's event loop, and all thread_sensitive synchronous code will run in a single shared sub-thread.

Cruicially, this means that in both cases there is a thread which is a shared resource that all thread_sensitive code must run on, and there is a chance that this thread is currently blocked on its own AsyncToSync call. Thus, AsyncToSync needs to act as an executor for thread code while it's blocking.

The CurrentThreadExecutor class provides this functionality; rather than simply waiting on a Future, you can call its run_until_future method and it will run submitted code until that Future is done. This means that code inside the call can then run code on your thread.

Maintenance and Security

To report security issues, please contact [email protected]. For GPG signatures and more security process information, see https://docs.djangoproject.com/en/dev/internals/security/.

To report bugs or request new features, please open a new GitHub issue.

This repository is part of the Channels project. For the shepherd and maintenance team, please see the main Channels readme.

Hypothesis is a powerful, flexible, and easy to use library for property-based testing.

Hypothesis Hypothesis is a family of testing libraries which let you write tests parametrized by a source of examples. A Hypothesis implementation the

Hypothesis 6.4k Jan 01, 2023
Official mirror of https://gitlab.com/pgjones/hypercorn https://pgjones.gitlab.io/hypercorn/

Hypercorn Hypercorn is an ASGI web server based on the sans-io hyper, h11, h2, and wsproto libraries and inspired by Gunicorn. Hypercorn supports HTTP

Phil Jones 432 Jan 08, 2023
ASGI specification and utilities

asgiref ASGI is a standard for Python asynchronous web apps and servers to communicate with each other, and positioned as an asynchronous successor to

Django 1.1k Dec 29, 2022
Green is a clean, colorful, fast python test runner.

Green -- A clean, colorful, fast python test runner. Features Clean - Low redundancy in output. Result statistics for each test is vertically aligned.

Nathan Stocks 756 Dec 22, 2022
A screamingly fast Python 2/3 WSGI server written in C.

bjoern: Fast And Ultra-Lightweight HTTP/1.1 WSGI Server A screamingly fast, ultra-lightweight WSGI server for CPython 2 and CPython 3, written in C us

Jonas Haag 2.9k Dec 21, 2022
PyQaver is a PHP like WebServer for Python.

PyQaver is a PHP like WebServer for Python.

Dev Bash 7 Apr 25, 2022
Robyn is an async Python backend server with a runtime written in Rust, btw.

Robyn is an async Python backend server with a runtime written in Rust, btw. Python server running on top of of Rust Async RunTime. Installation

Sanskar Jethi 1.8k Dec 30, 2022
Let your Python tests travel through time

FreezeGun: Let your Python tests travel through time FreezeGun is a library that allows your Python tests to travel through time by mocking the dateti

Steve Pulec 3.5k Jan 09, 2023
A utility for mocking out the Python Requests library.

Responses A utility library for mocking out the requests Python library. Note Responses requires Python 2.7 or newer, and requests = 2.0 Installing p

Sentry 3.8k Jan 02, 2023
Python HTTP Server

Python HTTP Server Preview Languange and Code Editor: How to run? Download the zip first. Open the http.py and wait 1-2 seconds. You will see __pycach

SonLyte 16 Oct 21, 2021
A test fixtures replacement for Python

factory_boy factory_boy is a fixtures replacement based on thoughtbot's factory_bot. As a fixtures replacement tool, it aims to replace static, hard t

FactoryBoy project 3k Jan 05, 2023
Waitress - A WSGI server for Python 2 and 3

Waitress Waitress is a production-quality pure-Python WSGI server with very acceptable performance. It has no dependencies except ones which live in t

Pylons Project 1.2k Dec 30, 2022
splinter - python test framework for web applications

splinter - python tool for testing web applications splinter is an open source tool for testing web applications using Python. It lets you automate br

Cobra Team 2.6k Dec 27, 2022
Mixer -- Is a fixtures replacement. Supported Django, Flask, SqlAlchemy and custom python objects.

The Mixer is a helper to generate instances of Django or SQLAlchemy models. It's useful for testing and fixture replacement. Fast and convenient test-

Kirill Klenov 871 Dec 25, 2022
HTTP client mocking tool for Python - inspired by Fakeweb for Ruby

HTTPretty 1.0.5 HTTP Client mocking tool for Python created by Gabriel Falcão . It provides a full fake TCP socket module. Inspired by FakeWeb Github

Gabriel Falcão 2k Jan 06, 2023
A drop-in replacement for Django's runserver.

About A drop in replacement for Django's built-in runserver command. Features include: An extendable interface for handling things such as real-time l

David Cramer 1.3k Dec 15, 2022
Mimesis is a high-performance fake data generator for Python, which provides data for a variety of purposes in a variety of languages.

Mimesis - Fake Data Generator Description Mimesis is a high-performance fake data generator for Python, which provides data for a variety of purposes

Isaak Uchakaev 3.8k Jan 01, 2023
Scalable user load testing tool written in Python

Locust Locust is an easy to use, scriptable and scalable performance testing tool. You define the behaviour of your users in regular Python code, inst

Locust.io 20.4k Jan 08, 2023
A cross-platform GUI automation Python module for human beings. Used to programmatically control the mouse & keyboard.

PyAutoGUI PyAutoGUI is a cross-platform GUI automation Python module for human beings. Used to programmatically control the mouse & keyboard. pip inst

Al Sweigart 7.6k Jan 01, 2023
create custom test databases that are populated with fake data

About Generate fake but valid data filled databases for test purposes using most popular patterns(AFAIK). Current support is sqlite, mysql, postgresql

Emir Ozer 2.2k Jan 06, 2023