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

技术栈

实现功能

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

效果展示

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

后端接口

  • 发送消息
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)
相关推荐
随便写个昵称9 小时前
django操作静态页面后返回提示
python·django·sqlite
快乐非自愿10 小时前
2026年Django生态现代化组件深度解析与实践
数据库·django·sqlite
㱘郳10 小时前
Python开发 Django和DRF框架 推荐部分B站视频
开发语言·python·django
ding_zhikai10 小时前
【Web应用开发笔记】Django笔记8:用户账户相关功能
笔记·后端·python·django
Mr数据杨10 小时前
【Dv3Admin】Django动态配置首页仪表盘
python·django·sqlite
程序设计实验室7 天前
分享一些2026年有意思的现代化Django生态组件
django
程序设计实验室8 天前
当人人都能用 AI 写代码时,我为什么选择重回 Django?
django·djangostarter
markfeng813 天前
Python+Django+H5+MySQL项目搭建
python·django
QQ40220549614 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
百锦再14 天前
Django实现接口token检测的实现方案
数据库·python·django·sqlite·flask·fastapi·pip