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

下载

相关推荐
烛阴29 分钟前
武装你的Python“工具箱”:盘点10个你必须熟练掌握的核心方法
前端·python
杨枝甘露小码1 小时前
Python学习之基础篇
开发语言·python
我是华为OD~HR~栗栗呀2 小时前
23届考研-Java面经(华为OD)
java·c++·python·华为od·华为·面试
小蕾Java2 小时前
PyCharm 软件使用各种问题 ,解决教程
ide·python·pycharm
Lucky_Turtle2 小时前
【PyCharm】设置注释风格,快速注释
python
kunge1v52 小时前
学习爬虫第四天:多任务爬虫
爬虫·python·学习·beautifulsoup
萧鼎3 小时前
Python schedule 库全解析:从任务调度到自动化执行的完整指南
网络·python·自动化
B站_计算机毕业设计之家4 小时前
机器学习实战项目:Python+Flask 汽车销量分析可视化系统(requests爬车主之家+可视化 源码+文档)✅
人工智能·python·机器学习·数据分析·flask·汽车·可视化
羊羊小栈4 小时前
基于「多模态大模型 + BGE向量检索增强RAG」的航空维修智能问答系统(vue+flask+AI算法)
vue.js·人工智能·python·语言模型·flask·毕业设计
星期天要睡觉4 小时前
模型部署——Flask 部署 PyTorch 模型
pytorch·python·flask