21
loading...
This website collects cookies to deliver better user experience
WSGI - WSGI is the Web Server Gateway Interface. It is a specification that describes how a web server communicates with web applications, and how web applications can be chained together to process one request. It's like a mediator for carrying out interaction between a web server and a python application.
ASGI - ASGI (Asynchronous Server Gateway Interface) is a spiritual successor to WSGI, intended to provide a standard interface between async-capable Python web servers, frameworks, and applications.
When a request or new socket comes in, Channels will follow its routing table, then find the right consumer for that incoming connection, and start up a copy of it. More on this later.
pip install django
django-admin startproject config .
pip install channels
INSTALLED_APPS = [
# ...
'channels',
]
import os
import django
from channels.http import AsgiHandler
from channels.routing import ProtocolTypeRouter
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()
application = ProtocolTypeRouter({
"http": AsgiHandler(),
# We will add WebSocket protocol later, but for now it's just HTTP.
})
ASGI_APPLICATION = "config.asgi.application"
python manage.py runserver
and you will see the following:python manage.py startapp chat
INSTALLED_APPS = [
# ...
'chat',
]
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Chat Room</title>
</head>
<body>
What chat room would you like to enter?<br>
<input id="room-name-input" type="text" size="100"><br>
<input id="room-name-submit" type="button" value="Enter">
<script>
document.querySelector('#room-name-input').focus();
document.querySelector('#room-name-input').onkeyup = function(e) {
if (e.keyCode === 13) { // enter, return
document.querySelector('#room-name-submit').click();
}
};
document.querySelector('#room-name-submit').onclick = function(e) {
var roomName = document.querySelector('#room-name-input').value;
window.location.pathname = '/chat/' + roomName + '/';
};
</script>
</body>
</html>
from django.shortcuts import render
def index(request):
return render(request, 'chat/index.html')
index
view to the url patterns.from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('chat/', include('chat.urls')),
]
python manage.py runserver