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

技术栈

实现功能

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

效果展示

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

后端接口

  • 发送消息
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)
相关推荐
Elaine3361 小时前
基于Django框架的静态个人名片网站设计
后端·python·django·mvt
2601_961194023 小时前
考研资料电子版|下载|pdf
java·python·考研·eclipse·django·pdf·pygame
我有2只猫20 小时前
LabelStudio二次开发
人工智能·python·django·ocr
大刚测试开发实战1 天前
TestHub测试平台整体功能简介
django·llm·测试
Wonderful U2 天前
Python+Django实战:打造智能生鲜果蔬进销存管理系统(采购入库、库存预警、销售开单、毛利统计)
数据库·python·django
*neverGiveUp*3 天前
初步了解Django框架
开发语言·python·django
2601_961194023 天前
2026四级词汇闪过电子版|高频词+真题词速记PDF
数据库·python·django·pdf·pygame
Wonderful U3 天前
基于Python+Django+MySQL构建个人任务管理系统:告别零散记录,实现高效日程管理
python·mysql·django
Wonderful U3 天前
基于Python+Django的文件预览与转换系统:从架构设计到完整实现
后端·python·django
*neverGiveUp*3 天前
Django ORM
后端·python·django