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

技术栈

实现功能

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

效果展示

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

后端接口

  • 发送消息
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)
相关推荐
MZ_ZXD00112 小时前
flask校园学科竞赛管理系统-计算机毕业设计源码12876
java·spring boot·python·spring·django·flask·php
LuckyLay13 小时前
1.1.5 模块与包——AI教你学Django
python·django·sqlite
LuckyLay13 小时前
Django专家成长路线知识点——AI教你学Django
后端·python·django
Q_Q196328847514 小时前
python的平安驾校管理系统
开发语言·spring boot·python·django·flask·node.js·php
小王子10241 天前
Django 实战:Celery 异步任务从环境搭建到调用全掌握
django·celery
Q_Q5110082851 天前
python的婚纱影楼管理系统
开发语言·spring boot·python·django·flask·node.js·php
暴走的海鸽2 天前
存储库模式赋能 Django:让你的代码不那么业余,更具生命力
python·设计模式·django
-dzk-2 天前
【Flask】基础入门
后端·python·pycharm·django·flask·conda·pip
noravinsc2 天前
django queryset 去重
数据库·django·sqlite