ASGI Introduction 🎯

beginner
13 min

ASGI Introduction 🎯

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!

Understanding ASGI πŸ“

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.

Why ASGI? πŸ’‘

ASGI streamlines the development process, making it easier to handle asynchronous operations, which are crucial for real-time applications and improving performance.

Getting Started with ASGI in Django βœ…

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:

bash
django-admin startproject my_project

Now, navigate to the project directory:

bash
cd my_project

Installing ASGI πŸ“

To install ASGI, you'll need to add it to your project's requirements. Here's how:

  1. Open my_project/requirements.txt file and add channels[asgi] to the end of the file:
channels[asgi]
  1. Run pip install -r requirements.txt to install ASGI.

Configuring Django for ASGI πŸ’‘

Now, let's make some changes to our project's settings:

  1. Open my_project/settings.py file and find the INSTALLED_APPS section. Add asgiapp (you'll create this later):
python
INSTALLED_APPS = [ # ... 'asgiapp', ]
  1. Add the following to the bottom of the file:
python
async_urls = 'asgiapp.urls'
  1. Now, create the asgiapp directory and urls.py file inside it:
bash
mkdir my_project/asgiapp touch my_project/asgiapp/urls.py

Creating an ASGI Application 🎯

Now, let's create a simple ASGI application. Open my_project/asgiapp/urls.py and add the following code:

python
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.

Creating a WebSocket Consumer πŸ’‘

Create a new file my_app/consumers.py and add the following code:

python
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:

bash
python manage.py runasgi my_project.asgiapp.application

You can now connect to the WebSocket using a WebSocket client, like WebSocket.js.

Wrapping Up βœ…

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.

Quick Quiz
Question 1 of 1

What is ASGI used for?