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

技术栈

实现功能

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

效果展示

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

后端接口

  • 发送消息
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)
相关推荐
右耳朵猫AI2 小时前
Python周刊2026W22 | Django 6.1 Alpha 1发布、Nuitka 4.1发布、PEP 831终稿、PEP 808已接受
开发语言·python·django
Wonderful U2 小时前
Python+Django实战|美食菜谱分享与食材采购一体化系统:食谱发布收藏、图文教程、食材商城、购物车、订单管理、美食点评、智能食谱推荐
python·django·美食
Elaine3361 天前
基于Django框架的静态个人名片网站设计
后端·python·django·mvt
2601_961194021 天前
考研资料电子版|下载|pdf
java·python·考研·eclipse·django·pdf·pygame
我有2只猫2 天前
LabelStudio二次开发
人工智能·python·django·ocr
大刚测试开发实战2 天前
TestHub测试平台整体功能简介
django·llm·测试
Wonderful U3 天前
Python+Django实战:打造智能生鲜果蔬进销存管理系统(采购入库、库存预警、销售开单、毛利统计)
数据库·python·django
*neverGiveUp*4 天前
初步了解Django框架
开发语言·python·django
2601_961194024 天前
2026四级词汇闪过电子版|高频词+真题词速记PDF
数据库·python·django·pdf·pygame
Wonderful U4 天前
基于Python+Django+MySQL构建个人任务管理系统:告别零散记录,实现高效日程管理
python·mysql·django