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

技术栈

实现功能

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

效果展示

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

后端接口

  • 发送消息
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)
相关推荐
凡梦千华12 小时前
django迁移表结构和数据
数据库·django
猎人everest14 小时前
Django Rest Framework (DRF) 核心知识体系梳理与深度讲解
后端·python·django
码界奇点15 小时前
基于Django与Ansible的智能运维管理系统设计与实现
运维·python·django·毕业设计·ansible·源代码管理
Q_Q5110082851 天前
python+django/flask+vue的大健康养老公寓管理系统
spring boot·python·django·flask·node.js
非鱼feiyu1 天前
自关联数据表查询优化实践:以 Django + 递归 CTE 构建树结构为例
数据库·后端·django
Q_Q19632884751 天前
python+django/flask+vue的多媒体素材管理系统
spring boot·python·django·flask·node.js·php
ServBay1 天前
Django 6.0 发布,新增原生任务队列与 CSP 支持
后端·python·django
Q_Q5110082851 天前
python+django/flask+vue农业电商服务系统
spring boot·python·pycharm·django·flask
Q_Q5110082851 天前
python+django/flask+vue的基于疫情防控管理系统的数据可视化分析系统
spring boot·python·django·flask·node.js
计算机学姐1 天前
基于Python的校园美食推荐系统【2026最新】
开发语言·vue.js·后端·python·mysql·django·推荐算法