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

技术栈

实现功能

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

效果展示

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

后端接口

  • 发送消息
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)
相关推荐
计算机学姐11 小时前
基于Python的商场停车管理系统【2026最新】
开发语言·vue.js·后端·python·mysql·django·flask
Cherry的跨界思维18 小时前
5、Python长图拼接终极指南:Pillow/OpenCV/ImageMagick三方案
javascript·python·opencv·webpack·django·pillow·pygame
陌上倾城落蝶雨19 小时前
django基础命令
后端·python·django
顾安r20 小时前
12.8 脚本网页 井字棋
前端·stm32·django·html
DreamNotOver20 小时前
在 VS Code 中使用 Conda虚拟环境高效运行与调试 Django 单元测试
python·django·conda
Cherry的跨界思维20 小时前
8、Python正则表达式精准搜索实战:从模糊匹配到精准定位
开发语言·python·正则表达式·django·flask·pygame·tornado
清静诗意20 小时前
Django REST Framework(DRF)PATCH 方法部分更新全解析与实战
后端·python·django
A小辣椒2 天前
Vue + Django 项目部署指南
django
A小辣椒2 天前
Django 项目数据库迁移 + 旧数据导入
django
大叔_爱编程2 天前
基于大数据的短视频用户兴趣分析-hive+django+spider
大数据·hive·django·毕业设计·源码·课程设计·spider