首先!
cd C:\builds\django_channels_realtime\django_channels
python3 manage.py startapp chat
python3 -m pip install -U 'channels[daphne]'
建立後專案結構為
chat/
__init__.py
admin.py
apps.py
models.py
tests.py
views.py
接下來會需要再 django_channels/settings.py 新增程式碼
(接下來範例都會使用 # + 路徑來代表開啟哪個檔案)
# django_channels/settings.py
import os # 新增
...
ASGI_APPLICATION = "django_channels.asgi.application"
...
INSTALLED_APPS = [
'chat', # 新增
'daphne',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
...
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'chat', 'templates')], # 新增
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
建立新的HTML檔案,用來呈現聊天室的網頁
位置:django_channels/chat/templates/chat/index.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.key === 'Enter') { // 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>
以上為建立聊天室的HTML,
# chat/views.py
from django.shortcuts import render
def index(request):
return render(request, "chat/index.html")
建立 django 和 html 的關聯
# chat/urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
]
建立網頁地址與網頁呈現的關聯
# django_channels/urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path("chat/", include("chat.urls")),
path("admin/", admin.site.urls),
]
建立根目錄與分支的網址關聯
意含透過 /chat/ -> 呈現 index.html 的程式碼
# django_channels/asgi.py
import os
from channels.routing import ProtocolTypeRouter
from django.core.asgi import get_asgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_channels.settings") #這段告訴 django 他的設定目錄在哪裡
application = ProtocolTypeRouter(
{
"http": get_asgi_application(),
# Just HTTP for now. (We can add other protocols later.)
}
)
python3 manage.py runserver
執行上述指令表示建立一個網站伺服器
在瀏覽器輸入
http://127.0.0.1:8000/chat/
應該要看到
恭喜完成上半部範例