【即时通讯】轮询方式实现

技术栈

实现功能

  • 首次访问页面并发送消息时需要设置昵称
  • 发送内容为空时要提示用户不能发送空消息
  • 前端定时获取消息,然后展示在页面上。

效果展示

  • 首次发送需要设置昵称
  • 发送消息与消息展示
  • 提示用户不能发送空消息

后端接口

  • 发送消息
python 复制代码
DB = []
@router.post("/poll/send/message")
def send_message_api(request: WSGIRequest, message: MessageSchema) -> JsonResponse:
    """
    轮询通讯接收消息接口
    :param request: WSGIRequest
    :param message: MessageSchema
    :return: JsonResponse
    """
    message_info = message.dict()
    DB.append(message_info)
    return JsonResponse({"ok": True})
  • 获取消息
python 复制代码
@router.get("/poll/get/messages")
def get_messages_api(request: WSGIRequest, startIndex: int) -> JsonResponse:
    """
    轮询通讯获取消息接口
    :param request: WSGIRequest
    :param startIndex: int 上次获取聊天记录的最后位置
    """
    context = {
        "data": DB[startIndex:],
        "maxIndex": len(DB)
    }
    return JsonResponse(context)
相关推荐
2601_961875242 小时前
花生十三资源盘|电子版|全科
python·django·flask·virtualenv·scikit-learn·pygame·tornado
码云骑士3 小时前
28-Docker部署Django(下)-docker-compose编排与静态文件处理
docker·容器·django
码云骑士5 小时前
23-Django-ORM的N+1问题-select_related与prefetch_related详解
后端·python·django
摸摸芋7 小时前
Django框架(1)
后端·python·django
码云骑士7 小时前
27-Docker部署Django(上)-从2GB到180MB的镜像瘦身实战
docker·容器·django
杰杰7987 小时前
DRF的分页讲解-入门篇 三个基础分页类介绍
python·django
王小王-1237 小时前
基于电脑硬件市场数据分析与可视化系统
数据库·数据分析·django·sqlite·电脑·电脑硬件数据·电脑硬件市场分析
码云骑士8 小时前
25-数据库连接池-Django连接复用与连接数上限控制
数据库·python·django
码云骑士8 小时前
22-接手Django老项目(下)-读懂urls路由树与架构脉络
python·架构·django
码云骑士8 小时前
24-Django请求全链路-WSGI到数据库响应的完整旅程
数据库·python·django