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

技术栈

实现功能

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

效果展示

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

后端接口

  • 发送消息
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)
相关推荐
多想和从前一样5 小时前
Django 创建表时 “__str__ ”方法的使用
后端·python·django
chusheng184014 小时前
基于 Python 和 Django 的北极星招聘数据可视化系统(附源码,部署)
python·信息可视化·django·python 招聘数据·python 招聘数据可视化
明月看潮生21 小时前
青少年编程与数学 02-009 Django 5 Web 编程 19课题、RESTful API开发
python·青少年编程·django·restful·编程与数学
木制品1231 天前
Django后台新建管理员
数据库·django·sqlite
m0_748237051 天前
【玩转全栈】----Django模板语法、请求与响应
数据库·python·django
m0_748248231 天前
从零创建一个 Django 项目
后端·python·django
web182854825122 天前
Python毕业设计选题:基于django+vue的宠物服务管理系统
python·django·课程设计
木制品1232 天前
Django中数据库迁移命令
数据库·django·sqlite
web135085886352 天前
【玩转全栈】----Django基本配置和介绍
数据库·django·sqlite
明月看潮生2 天前
青少年编程与数学 02-009 Django 5 Web 编程 16课题、权限管理
python·青少年编程·django·编程与数学·授权与认证