1.第一部分:基础设置
Channels3.0支持Python3.6和Django2.2+
1.1项目结构
mysite/
manage.py
mysite/
__init__.py
asgi.py
settings.py
urls.py
wsgi.py
1.2自建项目主要文件夹
chat/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
views.py
1.3移除不必须文件,保留必须文件,像这样
chat/
__init__.py
views.py
1.4在INSTALLED_APPS加入项目名
# mysite/settings.py
INSTALLED_APPS = [
'chat',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
1.5创建聊天首页view
1.5.1在templates文件夹创建一个html文件
chat/
__init__.py
templates/
chat/
index.html
views.py
html代码
<!-- chat/templates/chat/index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Chat Rooms</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>
1.6在view创建接受前端请求,返回html
# chat/views.py
from django.shortcuts import render
def index(request):
return render(request, 'chat/index.html')
1.7在路由端chat/urls.py添加路径
# chat/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
1.8在路由端mysite/urls.py添加路径
# mysite/urls.py
from django.conf.urls import include
from django.urls import path
from django.contrib import admin
urlpatterns = [
path('chat/', include('chat.urls')),
path('admin/', admin.site.urls),
]
1.9可以运行了
python3 manage.py runserver
这里有两个连接
http://127.0.0.1:8000/chat/lobby/这个连接可能会404,因为还没有整合channels
1.10修改mysite/Saginaw.py
# mysite/asgi.py
import os
from channels.routing import ProtocolTypeRouter
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
application = ProtocolTypeRouter({
"http": get_asgi_application(),
# Just HTTP for now. (We can add other protocols later.)
})
1.11在mysite/settings.py的INSTALLED_APP 添加channels
# mysite/settings.py
INSTALLED_APPS = [
'channels',
'chat',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
1.12在mysite/settings.py添加指向Channels
# mysite/settings.py
# Channels
ASGI_APPLICATION = 'mysite.asgi.application'
1.13再次运行
python3 manage.py

本文详细介绍了如何使用Python3.6和Django结合channels库构建一个实时聊天室。从基础设置开始,包括项目结构、视图、路由配置,到聊天室服务器接口的实现,再到异步重写聊天室和自动化测试的步骤,一步步指导读者完成WebSocket聊天室的搭建。最后提供了深入学习的资源链接。
最低0.47元/天 解锁文章

546

被折叠的 条评论
为什么被折叠?



