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

技术栈

实现功能

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

效果展示

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

后端接口

  • 发送消息
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)
相关推荐
开开心心_Every6 小时前
手机端课程表管理工具:支持课程导入自定义
python·游戏·微信·django·pdf·excel·语音识别
飞天小蜈蚣6 小时前
python-django_ORM的十三个查询API接口
开发语言·python·django
WangYaolove13147 小时前
基于人脸表情的分类算法的设计(源码+文档)
python·mysql·django·毕业设计·源码
开开心心_Every7 小时前
安卓语音转文字工具:免费支持实时转换视频
python·游戏·微信·django·pdf·excel·语音识别
WangYaolove13148 小时前
基于图像取证技术研究与实现(源码+文档)
python·django·毕业设计·源码·计算机源码
飞Link1 天前
【Django】Django的静态文件相关配置与操作
后端·python·django
践行见远2 天前
django之序列化
android·数据库·django
Red丶哞3 天前
[Django Message超全总结教程](武沛齐老师)
数据库·django·sqlite
曲幽3 天前
Django入门指南:Python Web开发的“瑞士军刀”
python·django·flask·fastapi·web·pythonweb