Welcome to our comprehensive guide on ASGI (ASynchronous Server Gateway Interface)! In this lesson, we'll delve into the world of ASGI, understanding its importance, and learning how to use it in your Django projects. Let's get started!
ASGI is a new standard for building web applications using Python. It simplifies the process by providing a single interface for various WebSockets and HTTP servers, replacing Django's built-in synchronous servers.
ASGI streamlines the development process, making it easier to handle asynchronous operations, which are crucial for real-time applications and improving performance.
To get started, make sure you have Python 3.7+ and Django 3.2+ installed. If you haven't, you can find the installation guides here.
Next, let's create a new Django project:
django-admin startproject my_projectNow, navigate to the project directory:
cd my_projectTo install ASGI, you'll need to add it to your project's requirements. Here's how:
my_project/requirements.txt file and add channels[asgi] to the end of the file:channels[asgi]
pip install -r requirements.txt to install ASGI.Now, let's make some changes to our project's settings:
my_project/settings.py file and find the INSTALLED_APPS section. Add asgiapp (you'll create this later):INSTALLED_APPS = [
# ...
'asgiapp',
]async_urls = 'asgiapp.urls'asgiapp directory and urls.py file inside it:mkdir my_project/asgiapp
touch my_project/asgiapp/urls.pyNow, let's create a simple ASGI application. Open my_project/asgiapp/urls.py and add the following code:
import os
from django.urls import re_path, include
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from my_app.consumers import MyConsumer
application = ProtocolTypeRouter({
"http": get_asgi_application(),
"websocket": AuthMiddlewareStack(
URLRouter([
re_path(r"ws/my-channel/$", MyConsumer),
])
),
})
def get_asgi_application():
return DjangoASGI(os.path.abspath(os.path.dirname(__file__)))In the code above, we define an ASGI application that includes an HTTP server and a WebSocket consumer. The consumer is not yet created, so let's do that now.
Create a new file my_app/consumers.py and add the following code:
import asyncio
import json
from channels.generic.websocket import AsyncWebsocketConsumer
class MyConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.room_name = self.scope["url_route"]["kwargs"]["room_name"]
self.room_group_name = f"my_app.{self.room_name}"
await self.channel_layer.groups.add(
self.room_group_name,
self.channel_name
)
await self.accept()
await self.send(text_data=json.dumps({
"type": "connect",
"room": self.room_name
}))
async def disconnect(self, close_code):
await self.channel_layer.groups.discard(
self.room_group_name,
self.channel_name
)
async def receive(self, text_data):
text_data_json = json.loads(text_data)
room = text_data_json["room"]
await self.channel_layer.group_send(
self.room_group_name,
{
"type": "chat_message",
"room": room,
"message": text_data_json["message"]
}
)
async def chat_message(self, event):
message = event["message"]
await self.send(text_data=json.dumps({
"type": "chat_message",
"message": message
}))Now, your ASGI application is ready! To test it, run the following command:
python manage.py runasgi my_project.asgiapp.applicationYou can now connect to the WebSocket using a WebSocket client, like WebSocket.js.
Congratulations! You've learned the basics of ASGI in Django. In the next lessons, we'll dive deeper into ASGI, exploring more advanced topics like middleware, testing, and deploying ASGI applications.
What is ASGI used for?