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

技术栈

实现功能

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

效果展示

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

后端接口

  • 发送消息
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)
相关推荐
新时代牛马7 小时前
镜像为什么越来越大?从Dockerfile、layer 到content-addressable store 讲透
django
专业程序开发源9 小时前
springbootLivehouse票务系统-计算机课程设计、毕业设计
vue.js·spring boot·后端·python·django·课程设计·pygame
李高钢9 小时前
Python Django 框架入门:从零搭建你的第一个 Web 应用
前端·python·django
troy1281 天前
分布式系统框架选型指南:主流框架优缺点深度对比
python·django·pygame
IT毕设实战小研2 天前
基于大数据的跨国外派人员适应满意度与留存影响因素可视化分析
android·java·大数据·python·django·课程设计
烂蜻蜓2 天前
Django入门教程(三):django-admin与manage.py命令完全指南
数据库·django·sqlite
2601_962283884 天前
Django数据库配置(一)
mysql·postgresql·django·sqlite·数据库配置
qq_22589174665 天前
基于Python+Django的LangGraph智能旅游规划系统
python·django·旅游
小刘在重生~6 天前
Django|Excel 批量上传、Form/ModelForm 文件上传、Media 媒体文件配置
python·django·excel
小刘在重生~6 天前
Django|Ajax 入门、JSON 返回、ECharts 图表、文件上传完整笔记
ajax·django·json