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

技术栈

实现功能

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

效果展示

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

后端接口

  • 发送消息
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)
相关推荐
qq_22589174662 小时前
基于Python的中药药材数据可视化分析系统
python·机器学习·数据分析·django
俊哥工具2 小时前
文件批量转换工具 本地运行更快更安全
运维·服务器·django·音视频·tornado
Python私教19 小时前
Django 6.1 RC1 实测:FETCH_PEERS 两条 SQL 解决 N+1,select_related 还需要吗?
后端·python·django
Python私教19 小时前
Django 6.0 自带 Tasks 到底能不能替代 Celery?跑完 3 组后台任务后我有答案了
后端·python·django
韭菜炒鸡肝天1 天前
Django模型迁移指南:从命令用法到最佳实践
数据库·django·sqlite
weixin_BYSJ19872 天前
springboot旅游景点以及美食地图小程序---附源码75422
java·javascript·c++·spring boot·python·django·php
qq_22589174663 天前
基于Python的城市内涝积涝监测数据可视化分析系统
后端·python·信息可视化·数据分析·django
米码收割机3 天前
【Python】Python Django+Vue3校园自习室预约管理系统(源码+文档+PPT)【独一无二】
开发语言·python·django
米码收割机3 天前
【移动】线上购物移动端网站(源码+文档)【独一无二】
java·开发语言·前端·python·django