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

技术栈

实现功能

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

效果展示

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

后端接口

  • 发送消息
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)
相关推荐
IT策士3 小时前
Django 从 0 到 1 打造完整电商平台:Admin 后台管理与数据初始化
数据库·django·sqlite
IT策士6 小时前
Django 从 0 到 1 打造完整电商平台:Django 模型进阶与数据迁移
python·django·sqlite
IT策士1 天前
Django 从 0 到 1 打造完整电商平台:为什么用 Django 做电商?
后端·python·django
zzzzzz3101 天前
VGGT-Ω 深度解读:用 30% 显存训练 15 倍数据,牛津&Meta 的 3D 视觉大一统之路
django
Muyuan19981 天前
31.Cursor 初体验:用 AI Agent 给 PaperPilot 做一次最小工程重构
人工智能·python·重构·django·fastapi·faiss
IT策士1 天前
Django 从 0 到 1 打造完整电商平台:电商项目需求分析与数据库设计
数据库·django·需求分析
creaDelight1 天前
Django 中间件钩子函数 & CBV vs FBV 实战验证
python·中间件·django
En^_^Joy2 天前
Django模型:数据库操作全指南
数据库·django·sqlite
__log3 天前
ComfyUI 集成技术方案分析报告
javascript·python·django
俊哥工具4 天前
鼠标自动连点怎么设置?详细教学,简单易懂!
python·django·pdf·计算机外设·virtualenv·pygame