- vừa được xem lúc

Django channels hướng dẫn cơ bản

0 0 55

Người đăng: Kính Gia Hà

Theo Viblo Asia

Giới thiệu

Channels kết hợp hỗ trợ chế độ xem không đồng bộ gốc của Django, cho phép các dự án của Django xử lý không chỉ HTTP mà còn các giao thức yêu cầu kết nối lâu dài - WebSockets, MQTT, chatbots, đài nghiệp dư, v.v.

Nó thực hitện điều này rong khi vẫn bảo toàn tính chất đồng bộ và dễ sử dụng của Django, cho phép bạn chọn cách bạn viết mã của mình - đồng bộ theo phong cách như chế độ xem Django, hoàn toàn không đồng bộ hoặc kết hợp cả hai. Trên hết, nó cung cấp tích hợp với hệ thống xác thực của Django, hệ thống phiên và hơn thế nữa, giúp việc mở rộng dự án chỉ HTTP của bạn sang các giao thức khác dễ dàng hơn bao giờ hết.

Channels cũng kết hợp kiến ​​trúc hướng sự kiện này với các lớp kênh , một hệ thống cho phép bạn dễ dàng giao tiếp giữa các quy trình và tách dự án của bạn thành các quy trình khác nhau.

Cài đặt

start app

django-admin startproject myapp
python3 manage.py startapp chat

Sau đó create urls.py trong app chat. thêm thư mục templates và tạo file chat.html trong templates

myapp
├─ myapp
│ ├─ __init__.py
│ ├─ asgi.py
│ ├─ settings.py
│ ├─ urls.py
│ └─ wsgi.py
├─ chat
│ ├─ __init__.py
│ ├─ admin.py
│ ├─ apps.py
│ ├─ models.py
│ ├─ tests.py
│ ├─ urls.py
│ └─ views.py
├─ templates
│ └─ chat.html
└─ manage.py

Tiếp đết chúng ta thêm app chat vào setting.py

# mysite/settings.py
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'chat',
]

Sửa file chat.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>

chỉnh sửa file urls.py trong app chat

# chat/urls.py
from django.urls import path
from . import views
urlpatterns = [ path('chat/', views.chat), path('chat/<str:room_name>/', views.chat_room),
]

chỉnh sửa views.py trong app chat

def chat(request): return render(request, 'chat.html') def chat_room(request, room_name): return render(request, 'room.html', {"room_name": room_name})

Chỉnh sửa file urls.py trong myapp

# myapp/urls.py
from django.conf.urls import include
from django.urls import path
from django.contrib import admin urlpatterns = [ path('admin/', admin.site.urls), path('', include('chat.urls')),
]

channels

pip install channels

Tiếp tục chỉnh sửa file setting.py

INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'chat', 'channels',
] ASGI_APPLICATION = 'myapp.asgi.application' CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer", }
}

Tạo routing.pyconsumers.py trong myapp

myapp
├─ myapp
│ ├─ __init__.py
│ ├─ asgi.py
│ ├─ consumers.py
│ ├─ routing.py
│ ├─ settings.py
│ ├─ urls.py
│ └─ wsgi.py
├─ chat
│ ├─ __init__.py
│ ├─ admin.py
│ ├─ apps.py
│ ├─ models.py
│ ├─ tests.py
│ ├─ urls.py
│ └─ views.py
├─ templates
│ └─ chat.html
└─ manage.py

Chỉnh sửa fie asgi.py trong myapp


from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter from myapp import routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( routing.ws_urlpatterns ) )
}) 

Chỉnh sửa file routing.py tron myapp

from django.urls import path from . import consumers ws_urlpatterns = [ path('ws/chat/<str:room_name>/', consumers.ChatConsumer.as_asgi()),
]

Chỉnh sửa file consumers.py trong myapp

import json
from channels.generic.websocket import AsyncWebsocketConsumer class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): print('connect') await self.accept() room_name = self.scope['url_route']['kwargs']['room_name'] await self.channel_layer.group_add(room_name, self.channel_name) print(f"Kết nối vào nhóm {self.channel_name}") async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] room_name = self.scope['url_route']['kwargs']['room_name'] await self.channel_layer.group_send( room_name, { 'type': 'chat_message', "message": message } ) async def chat_message(self, event): message = event['message'] await self.send(text_data=json.dumps({ 'message': message, })) async def disconnect(self, close_code): room_name = self.scope['url_route']['kwargs']['room_name'] await self.channel_layer.group_discard(room_name, self.channel_name) print(f"Thoát khỏi nhóm {self.channel_name}")

Tạo và chỉnh sửa file room.html trong templates

myapp
├─ myapp
│ ├─ __init__.py
│ ├─ asgi.py
│ ├─ consumers.py
│ ├─ routing.py
│ ├─ settings.py
│ ├─ urls.py
│ └─ wsgi.py
├─ chat
│ ├─ __init__.py
│ ├─ admin.py
│ ├─ apps.py
│ ├─ models.py
│ ├─ tests.py
│ ├─ urls.py
│ └─ views.py
├─ templates
│ ├─ chat.html
│ └─ room.html
└─ manage.py

<!DOCTYPE html>
<html> <head> <meta charset="utf-8" /> <title>Chat Room</title>
</head> <body> <textarea id="chat-log" cols="100" rows="20"></textarea><br> <input id="chat-message-input" type="text" size="100"><br> <input id="chat-message-submit" type="button" value="Send"> {{ room_name|json_script:"room_name" }} <script> const roomName = JSON.parse(document.getElementById('room_name').textContent); const chat = `ws://127.0.0.1:8000/ws/chat/${roomName}/` const chatSocket = new WebSocket(chat) chatSocket.onopen = function (e) { console.log("open", e); } chatSocket.onmessage = function(e) { const data = JSON.parse(e.data); document.querySelector('#chat-log').value += (data.message + '\n'); }; chatSocket.onerror = function (e) { console.log("error", e) } chatSocket.onclose = function (e) { console.log("close", e) } document.querySelector('#chat-message-input').focus(); document.querySelector('#chat-message-input').onkeyup = function (e) { if (e.keyCode === 13) { // enter, return document.querySelector('#chat-message-submit').click(); } }; document.querySelector('#chat-message-submit').onclick = function (e) { const messageInputDom = document.querySelector('#chat-message-input'); const message = messageInputDom.value; chatSocket.send(JSON.stringify({ 'message': message })); messageInputDom.value = ''; }; </script>
</body> </html>

Run app

python manage.py makemigrations
python manage.py migrate
python manage.py runserver

Chúc các bạn thành công!

Bình luận

Bài viết tương tự

- vừa được xem lúc

Lập trình socket bằng Python

Socket là gì. Một chức năng khác của socket là giúp các tầng TCP hoặc TCP Layer định danh ứng dụng mà dữ liệu sẽ được gửi tới thông qua sự ràng buộc với một cổng port (thể hiện là một con số cụ thể), từ đó tiến hành kết nối giữa client và server.

0 0 56

- vừa được xem lúc

Lập trình mạng với Java Swing + Socket

Xin chào mọi người trong bài này mình sẽ hướng dẫn các bạn thiết kế ra 1 form đơn giản có gửi nhận dữ liệu với Java Swing + Socket, IDE mình sử dụng là Eclipse mọi người nhé. Để cài đặt được windowbui

0 0 154

- vừa được xem lúc

Basic Socket Programming

1. Struct address. 1.1.

0 0 15

- vừa được xem lúc

Creating a Custom User Model in Django

Làm thế nào để thay thế username với email trong Django authentication. Cần chú ý rằng các làm này sẽ làm thay đổi rất nhiều đến schema của database vậy nên khuyến khích khi thực hiện một dự án mới.

0 0 23

- vừa được xem lúc

Câu chuyện kiểm soát truy cập trong Django.

Nếu bạn đang xây dựng một ứng dụng với Django, có thể bạn sẽ muốn kiểm soát quyền truy cập ứng với từng loại user. Những tính năng này sẽ phổ biến trên các trang web có quy mô lớn hơn một chút.

0 0 68

- vừa được xem lúc

Django: Handling CSV Data

Khi làm việc với các dự án Python hay Django thì phần xử lý CSV hầu như là không thể thiếu. Qua bài viết này, các bạn hãy cùng mình hiểu rõ hơn về CSV cũng như xử lý chúng ra sao nhé.

0 0 29