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

技术栈

实现功能

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

效果展示

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

后端接口

  • 发送消息
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)
相关推荐
treasure1401 小时前
Django复习笔记(2026年10月)
后端·python·django·api·web·drf
ycydynq1 天前
django 添加信息时,对外键设置条件
数据库·python·django
智购科技无人售货机厂家1 天前
自动售货机物联网平台为什么会出现在线状态不一致?~YH
python·单片机·嵌入式硬件·django·pygame
FYKJ_20102 天前
springboot高考志愿填报推荐系统14332-计算机课程设计、毕业设计
javascript·spring boot·python·架构·django·课程设计·高考
我的xiaodoujiao2 天前
Django 权限系统项目实战详细图文教程 3--系统登录功能实现
后端·python·django
我的xiaodoujiao2 天前
Django 权限系统项目实战详细图文教程 4--系统登录功能实现 2
后端·python·django
2501_944521593 天前
Immer 跨端三方库仓颉适配全流程
python·eclipse·django
2501_948122633 天前
Qs 跨端三方库仓颉适配全流程
python·react native·django·tornado
CS创新实验室3 天前
改了模型,数据库为什么能自动跟上?——Django 迁移(migrations)的底层
数据库·django·sqlite
weixin_BYSJ19874 天前
电竞先锋网站---附源码02032
java·vue.js·spring boot·python·django·tomcat·php