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

技术栈

实现功能

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

效果展示

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

后端接口

  • 发送消息
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)
相关推荐
Wonderful U1 天前
Python+Django实战:打造智能生鲜果蔬进销存管理系统(采购入库、库存预警、销售开单、毛利统计)
数据库·python·django
*neverGiveUp*2 天前
初步了解Django框架
开发语言·python·django
2601_961194022 天前
2026四级词汇闪过电子版|高频词+真题词速记PDF
数据库·python·django·pdf·pygame
Wonderful U2 天前
基于Python+Django+MySQL构建个人任务管理系统:告别零散记录,实现高效日程管理
python·mysql·django
Wonderful U2 天前
基于Python+Django的文件预览与转换系统:从架构设计到完整实现
后端·python·django
*neverGiveUp*2 天前
Django ORM
后端·python·django
智慧物业老杨2 天前
司法绿色通道下的物业纠纷数智化解决方案——基于“三优先“机制的全流程技术落地实践
java·django
天天进步20153 天前
Python全栈项目--社区问答平台
开发语言·python·django
二等饼干~za8986683 天前
geo优化系统源码搭建保姆式搭建教程
java·开发语言·django·php·音视频
Wonderful U3 天前
基于Python+Django的智能在线考试系统:从题库管理到自动阅卷的全流程实战
开发语言·python·django