초보자를 위한 Django WebSocket 튜토리얼
5022 단어 djangopythonwebsocketprogramming

다음 요구 사항을 설치하십시오.
장고
pip install django채널
pip install channels모든 요구사항을 설치한 후 프로젝트의
settings.py 파일을 업데이트하십시오. 설치된 앱 목록에 채널을 추가합니다. 아래를 참조하십시오.# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'channels'
]
이제 settings.py에 ASGI_APPLICATION을 추가해야 합니다. WSGI_APPLICATION 아래에 추가하겠습니다.
WSGI_APPLICATION = 'channelsdemo.wsgi.application'
ASGI_APPLICATION = 'channelsdemo.asgi.application'이제 consumer.py라는 파일을 만들고 WebSocketConsumer 클래스를 확장하는 NumberGenerator라는 클래스를 만듭니다. random.randint(1, 1000)을 사용하여 난수를 생성하는 루프를 만들고 json.dumps()는 사전을 텍스트로 변환합니다. 텍스트는
self.send()를 사용하여 클라이언트로 전송됩니다.import json
import random
from time import sleep
from channels.generic.websocket import WebsocketConsumer
class NumberGenerator(WebsocketConsumer):
def connect(self):
self.accept()
while True:
data = {
'number': random.randint(1, 1000)
}
self.send(json.dumps(data))
sleep(1)
def disconnect(self, code):
print("Socket disconnected with code", code)
asgi 앱의 URL 패턴
웹 소켓에 대한 새 URL 패턴을 생성합니다. Django urlpatterns와 동일합니다. 따라서 다음 패턴으로
ws_urlpatterns.py라는 파일을 만듭니다.from django.urls import path
from channelsdemo.consumers import NumberGenerator
ws_urlpatterns = [
path('ws/', NumberGenerator.as_asgi(), name='number-generator')
]
asgi.py 파일 수정
이 파일은 채널이 설치될 때 자동으로 생성됩니다. 앞에서 생성한 ws_urlpatterns.py를 사용합니다.
import os
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application
from channelsdemo.ws_urlpatterns import ws_urlpatterns
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'channelsdemo.settings')
application = ProtocolTypeRouter({
'http': get_asgi_application(),
'websocket': URLRouter(ws_urlpatterns)
})
이제 템플릿 디렉토리 안에 index.html을 생성해 봅시다. 그 전에 settings.py에 템플릿 디렉토리를 추가해야 합니다.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['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',
],
},
},
]
Index.html
WebSocket에서 오는 데이터를 모니터링하고 브라우저에 표시합니다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Websocket example</title>
</head>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #333;
}
#number {
font-size: 1.6rem;
color: white;
}
</style>
<body>
<p id="number"></p>
<script>
const socket = new WebSocket("ws://localhost:8000/ws/");
socket.onmessage = function (event) {
const data = JSON.parse(event.data);
console.log(data);
document.querySelector('#number').innerHTML = data.number;
}
</script>
</body>
</html>
사이트가 거의 완성되었습니다. Django 프로젝트에 몇 가지 뷰를 추가하기만 하면 됩니다.
views.py 파일을 만들고 다음 코드를 추가합니다.from django.shortcuts import render
def home(request):
return render(request, 'index.html')
이제 브라우저에서 매 초마다 난수가 변경되는 것을 볼 수 있습니다. 이 콘텐츠가 마음에 들면 여기에서 더 많은 기사를 확인하십시오.
Github URL: https://github.com/tejmagar/django-channels-websocket-example
Reference
이 문제에 관하여(초보자를 위한 Django WebSocket 튜토리얼), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/tejmagar/django-websocket-tutorial-for-begineers-gd9텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)