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

技术栈

实现功能

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

效果展示

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

后端接口

  • 发送消息
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
【赫兹威客】浩哥13 小时前
【无标题】
python·spring·django·pyqt
winfredzhang14 小时前
从零构建家庭照片管理系统:Django 模块化单体实战,以及我踩到的 4 个真实坑
python·postgresql·django·sqlite·bootsrap
weixin_BYSJ198718 小时前
springboot智慧公共交通系统---附源码51123
java·javascript·spring boot·python·django·flask·php
衿心.18 小时前
Django TemplateDoesNotExist
数据库·django·sqlite
weixin_BYSJ19872 天前
springboot游戏账号租赁系统---附源码50345
java·spring boot·python·游戏·django·flask·php
SelectDB技术团队3 天前
腾讯音乐内容库 ES 替代:从 Elasticsearch 到 Apache Doris 统一搜索分析引擎实践
elasticsearch·django·apache doris
willhu20084 天前
Windows 开机自动启动 Django 项目
后端·python·django
En^_^Joy4 天前
Django模板与静态文件使用指南
python·django·sqlite
weixin_BYSJ19874 天前
springboot小区物业管理小程序---附源码45555
java·javascript·spring boot·python·django·flask·php