FastAPI 学习之路(四十七)WebSockets(三)登录后才可以聊天

之前我们是通过前端自动生成的token信息,这次我们通过注册登录,保存到本地去实现。首先,我们实现一个登录页面,放在templates目录下。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
</head>
<body>
<div>
    <p><input id="username" placeholder="用户名"></p>
    <p><input id="password" placeholder="密码" type="password"></p>
    <button id="login">登录</button>
</div>
<script>
    $('#login').click(function () {
        $.ajax({
            type: "post",
            url: "/token",
             contentType: "application/json; charset=utf-8",
            data: JSON.stringify({
                email: $("#username").val(),
                password: $("#password").val()
            }),
            success: function (data) {
                if (data['msg'] == "success") {
                    window.localStorage.setItem("token", data['token'])
                    window.location.href="/"
                }else {
                    alert(data['msg'])
                }
            }
        })

    })
</script>
</body>
</html>

我们在后端去编写一个返回静态文件的页面,一个返回token的方法

def get_user_by_email(db: Session, email: str):
    user = db.query(User).filter(User.email == email).first()
    if not user:
        raise HTTPException(status_code=404, detail="this email not exists")
    return user



@app.get("/login")
async def login(request: Request):
    return templates.TemplateResponse(
        "login.html",
        {
            "request": request
        }
    )


@app.post("/token")
def generate_token(
        user: UserModel,
        db: Session = Depends(create_db)
):
    db_user = get_user_by_email(db, user.email)
    client_hash_password = user.password + "_hashed"
    if client_hash_password == db_user.hashed_password:
        return {"token": "lc-token-value", "msg": "success"}
    return {"token": None, "msg": "failed"}

然后我们可以去启动下,当我们启动完成登录后发现本地存了token,那么这个时候我们需要改造下webchat.html,我们取本地的 token,同时也实现了一个退出的功能。

<!DOCTYPE html>
<html>
<head>
    <title>Chat</title>
</head>
<body>
<h1>WebSocket 聊天</h1>
<form action="" onsubmit="sendMessage(event)">
    <input type="text" id="messageText" autocomplete="off"/>
    <button>Send</button>
</form>
<button onclick="logout()">退出</button>
<ul id='messages'>
</ul>
<script>
    var  token=window.localStorage.getItem("token")
    if (token==null ){
        window.location.href="/login"
    }
    var ws = new WebSocket("ws://localhost:8000/items/ws?token="+token);

    ws.onmessage = function (event) {

        var messages = document.getElementById('messages')

        var message = document.createElement('li')

        var content = document.createTextNode(event.data)

        message.appendChild(content)

        messages.appendChild(message)

    };

    function sendMessage(event) {

        var input = document.getElementById("messageText")

        ws.send(input.value)

        input.value = ''

        event.preventDefault()

    }
    function logout() {
        window.localStorage.removeItem("token")
        window.location.href='/login'
    }
</script>

</body>

</html>

这样我们就可以登录后,然后去获取登录产生的token,然后和后端发发送消息,这样我们完成了一个登录聊天,退出后无法聊天的功能。我们如果直接访问聊天的页面,也是可以直接去定向到我们的登录的界面呢,我们的聊天是依赖于我们的登录的。

成功后才可以发送聊天内容

点击退出,直接退出回到登录页

本地存储也清空了

相关推荐
黑金IT4 天前
WebSocket vs. Server-Sent Events:选择最适合你的实时数据流技术
网络·python·websocket·网络协议·fastapi
黑金IT4 天前
FastAPI 应用安全加固:HTTPSRedirectMiddleware 中间件全解析
安全·中间件·fastapi
写bug如流水5 天前
【FastAPI】实现服务器向客户端发送SSE(Server-Sent Events)广播
服务器·python·fastapi
黑金IT5 天前
从单体到微服务:FastAPI ‘挂载’子应用程序的转变
微服务·架构·fastapi
不良人龍木木5 天前
sqlalchemy FastAPI 前端实现数据库增删改查
前端·数据库·fastapi
写bug如流水6 天前
【FastAPI】离线使用Swagger UI 或 国内网络如何快速加载Swagger UI
ui·fastapi·命令模式
布响哒公8 天前
用python fastapi写一个http接口,使ros2机器人开始slam toolbox建图
python·机器人·fastapi
_.Switch9 天前
Python Web 框架篇:Flask、Django、FastAPI介绍及其核心技术
开发语言·前端·后端·python·django·flask·fastapi
黑金IT10 天前
深入FastAPI:掌握使用多个关联模型的高级用法[Union类型]
python·fastapi
黑金IT11 天前
深入理解FastAPI的response_model:自动化数据验证与文档生成
python·fastapi