django websocket

目录

核心代码

consumers.py

python 复制代码
from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer
import datetime
import time
from asgiref.sync import async_to_sync
class ChatConsumer(WebsocketConsumer):
    def websocket_connect(self, message):
        # 有客户端像后端发送websocket连接的请求时候,自动触发
        # 服务端允许和客户端创建连接
        self.accept()
    def websocket_receive(self, message):
        # 浏览器基于websocket想后端发送数据,自动触发接受消息
        print(f"接收到消息了:{message}")
        self.send("不要回复不要回复",datetime.datetime.now())
        #self.close() 这个是服务端主动断开连接
    def websocket_disconnect(self, message):
        # 客户端与服务器断开连接是,自动触发
        print("关闭连接")
        raise StopConsumer

tests.py

python 复制代码
import requests
url='http://127.0.0.1:8000/info/'
response=requests.post(url=url,json={'name':'张无忌','info':'太极'})
print(response.text)
``
views.py

```python
from django.shortcuts import render
from django.http import request,JsonResponse

# Create your views here.

def index(request):
    return render(request,'index.html',locals())

def info(request):
    if request.method=='POST':
        print(request.body.decode())
        return JsonResponse({'status':'success'})

index.html

python 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="/static/jquery-3.6.1.min.js"></script>
</head>
<body>
<div id="message">
<div>
    <input type="text" placeholder="请输入" id="txt">
    <input type="button" value="发送" onclick="sendMessage()">
</div>
</div>
<script>
    socket=new WebSocket("ws://127.0.0.1:8000/ws/group/")
    function sendMessage() {
        socket.send($("#txt").val())
        $("#txt").val('')
    }
    socket.onmessage=function  (event){
        console.log("接收到消息了收到了吗")
        console.log(event.data)
    }
    socket.onclose=function (event){
        console.log("断开连接")
    }
</script>
</body>
</html>

asgi.py

python 复制代码
import os

from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter,URLRouter
from dchannel import  routing

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dchannel.settings')

# application = get_asgi_application()
application=ProtocolTypeRouter({
    "http":get_asgi_application(),#自动去找urls.py,会找路由和视图函数-->http请求
    "websocket":URLRouter(routing.websocket_urlpatterns)#routing(urls),consumers(views)
})

routing.py

python 复制代码
from django.urls import re_path
from app01 import  consumers
websocket_urlpatterns={
    re_path(r'ws/(?P<group>\w+)/$',consumers.ChatConsumer.as_asgi())
}

urls.py

python 复制代码
from django.contrib import admin
from django.urls import path
from app01 import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/',views.index),
    path('info/',views.info)
]

下载

相关推荐
躺平的花卷17 分钟前
Python爬虫案例六:抓取某个地区某月份天气数据并保存到mysql数据库中
数据库·爬虫·python·mysql
虚拟搬运工18 分钟前
Python类及元类的创建流程
开发语言·chrome·python
学步_技术42 分钟前
Python编码系列—Python原型模式:深克隆与高效复制的艺术
开发语言·python·原型模式
Desire.9841 小时前
Python 数学建模——灰色关联度分析
python·数学建模·灰色关联度
小鹿( ﹡ˆoˆ﹡ )1 小时前
Python中的树与图:构建复杂数据结构的艺术
开发语言·python
阡之尘埃1 小时前
Python数据分析案例59——基于图神经网络的反欺诈交易检测(GCN,GAT,GIN)
python·神经网络·数据挖掘·数据分析·图神经网络·反欺诈·风控大数据
xiaojiesec2 小时前
第157天: 安全开发-Python 自动化挖掘项目&SRC 目标&FOFA 资产&Web 爬虫解析库
python·安全
27划流星雨_2 小时前
from tqdm.auto import tqdm用法详细介绍
python
爱里承欢。2 小时前
【Python语言初识(二)】
python
hzw05102 小时前
Jupyter的使用
ide·python·jupyter