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)
]

下载

相关推荐
没有梦想的咸鱼185-1037-16632 分钟前
【降尺度】ChatGPT+DeepSeek+python+CMIP6数据分析与可视化、降尺度技术与气候变化的区域影响、极端气候分析
python·chatgpt·数据分析
berryyan5 分钟前
傻瓜教程安装Trae IDE用AI撰写第一个AKShare接口脚本
python·trae
灏瀚星空22 分钟前
从基础到实战的量化交易全流程学习:1.3 数学与统计学基础——概率与统计基础 | 基础概念
笔记·python·学习·金融·概率论
Hellohistory27 分钟前
HOTP 算法与实现解析
后端·python
伊织code29 分钟前
cached-property - 类属性缓存装饰器
python·缓存·cache·装饰器·ttl·property·cached-property
明明跟你说过1 小时前
深度学习常见框架:TensorFlow 与 PyTorch 简介与对比
人工智能·pytorch·python·深度学习·自然语言处理·tensorflow
搏博1 小时前
专家系统的基本概念解析——基于《人工智能原理与方法》的深度拓展
人工智能·python·深度学习·算法·机器学习·概率论
yzx9910131 小时前
决策树随机深林
人工智能·python·算法·决策树·机器学习
梓羽玩Python1 小时前
月之暗面最新开源模型!Kimi-Audio:革新多模态音频处理,统一音频理解、生成与对话!
人工智能·python·github
noravinsc1 小时前
django admin 去掉新增 删除
python·django·sqlite