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

技术栈

实现功能

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

效果展示

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

后端接口

  • 发送消息
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)
相关推荐
沛沛老爹10 天前
Python Django全功能框架开发秘籍
python·django·orm·web开发·模板引擎·项目部署·表单处理
Q_Q196328847510 天前
python基于微信小程序的广西文化传承系统
开发语言·spring boot·python·微信小程序·django·flask
程序员爱钓鱼10 天前
Go Web开发框架实践:模板渲染与静态资源服务
后端·django·go
Q_Q196328847510 天前
python高校教务管理系统
开发语言·spring boot·python·django·flask·node.js·php
里探11 天前
Django中为api自定义一些装饰器:如参数校验等
python·django·装饰器模式
猫头虎11 天前
2025最新Python 100个常用函数在线体验项目
android·java·python·pycharm·django·pandas·pip
Q_Q51100828512 天前
python的校园兼职系统
开发语言·spring boot·python·django·flask·node.js·php
编程自留地12 天前
第14次:商品列表、热销商品及详情
python·django·商城
坤岭12 天前
Django项目搭建
django
noravinsc12 天前
django调用 paramiko powershell 获取cpu 个数
python·django·sqlite