Channels for Django in Python3

已发布 2018-04-10 16:02:25

Channels for django in Python3

Channels changes Django to weave asynchronous code underneath and through Django’s synchronous core, allowing Django projects to handle not only HTTP, but protocols that require long-running connections too - WebSockets, MQTT, chatbots, amateur radio, and more.

Concepts

  • Scopes: The scope is a set of details about a single incoming connection
  • Events: During the lifetime of this scope, a series of events occur.
  • Consumer: A consumer is the basic unit of Channels code. We call it a consumer as it consumes events, but you can think of it as its own tiny little application.

Write consumers

  • A consumer is a subclass of either channels.consumer.AsyncConsumer or channels.consumer.SyncConsumer
  • async def + await

Types of consumer:

  • WebsocketConsumer
  • AsyncWebsocketConsumer
  • JsonWebsocketConsumer
  • AsyncJsonWebsocketConsumer
  • AsyncHttpConsumer

Routing

  • URLRouter
  • ProtocolTypeRouter
  • ChannelNameRouter

Cross-Process Communication

However, as you build more complex application systems you start needing to communicate between different application instances.

You can do this by polling a database, but Channels introduces the idea of a channel layer, a low-level abstraction around a set of transports that allow you to send information between different processes. Each application instance has a unique channel name, and can join groups, allowing both point-to-point and broadcast messaging.

Django integration

Channels ships with easy drop-in support for common Django features, like sessions and authentication. You can combine authentication with your WebSocket views by just adding the right middleware around them.

comments powered by Disqus