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

技术栈

实现功能

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

效果展示

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

后端接口

  • 发送消息
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 U26 分钟前
基于Python+Django的智能在线考试系统:从题库管理到自动阅卷的全流程实战
开发语言·python·django
Wonderful U2 小时前
基于Python+Django的轻量化私有云盘系统:从零搭建安全可控的文件存储与共享平台
python·安全·django
Wonderful U19 小时前
Python+Django实战|个人博客内容管理系统:搭建轻量化、高自由度的个人动态博客CMS系统
人工智能·python·django
2601_961194021 天前
2026初级会计实务教材电子版|章节讲义+习题PDF
python·考研·django·pdf·virtualenv·pygame
2601_961194021 天前
2026初级会计经济法基础知识点汇总
python·django·pdf·virtualenv·代理模式·pygame
Wonderful U1 天前
Python+Django实战 | 智能图书管理系统:从传统人工到全自动数字化管理
python·信息可视化·django
2601_961194021 天前
考研政治历年真题库
python·考研·django·virtualenv·pygame·tornado
Wonderful U2 天前
基于 Django Channels 与 WebSocket 的实时聊天室:群聊、私聊、离线消息与持久化存储全实现
python·websocket·django
Wonderful U2 天前
Python+Django实战|校园二手闲置交易平台:从实名认证到交易闭环的完整校园电商解决方案
开发语言·python·django
Dxy12393102163 天前
Django 数据库 ENGINE 完全指南:选错了,性能差 10 倍
python·django