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

技术栈

实现功能

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

效果展示

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

后端接口

  • 发送消息
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)
相关推荐
小白勇闯网安圈12 小时前
Django Form 组件详解:从表单生成到 ModelForm 数据校验
数据库·django·sqlite
言乐612 小时前
Python实现随机抽人回答问题
开发语言·python·django·virtualenv·pygame
weixin_BYSJ198713 小时前
springboot技能与工具共享小程序---附源码29657
java·javascript·spring boot·python·小程序·django·php
weixin_BYSJ198713 小时前
flask民族服饰饰品商城小程序---附源码37399
java·javascript·spring boot·python·小程序·django·php
En^_^Joy1 天前
Django项目配置全攻略:settings配置文件
后端·python·django
小白勇闯网安圈2 天前
Django Ajax、批量操作与分页实践
python·django
言乐62 天前
Python游戏水平测试辅助系统2
开发语言·windows·python·游戏·django
vx-程序开发3 天前
springboot旅游推介平台---附源码24175
java·spring boot·python·spring cloud·eclipse·django·idea
言乐63 天前
Python游戏水平测试辅助系统
开发语言·python·游戏·django·pygame
小白勇闯网安圈3 天前
Django 响应对象、文件上传与类视图
数据库·django·sqlite