Flask-SocketIO和Flask-Login联合开发socketio权限系统

  1. 设置 Flask, Flask-SocketIO, Flask-Login:

首先,确保安装了必要的库:

bash 复制代码
pip install Flask Flask-SocketIO Flask-Login
  1. 基础设置:
python 复制代码
from flask import Flask, render_template, redirect, url_for, request
from flask_socketio import SocketIO, emit
from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required, current_user

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'
socketio = SocketIO(app)
login_manager = LoginManager(app)
login_manager.login_view = 'login'

# Dummy user store
users = {"testuser": {"password": "password123"}}

class User(UserMixin):
    def __init__(self, id):
        self.id = id

@login_manager.user_loader
def load_user(user_id):
    return User(user_id)
  1. 定义登录路由:
python 复制代码
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        if username in users and users[username]['password'] == password:
            user = User(username)
            login_user(user)
            return redirect(url_for('index'))
    return render_template('login.html')

@app.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('login'))
  1. 定义 SocketIO 路由并进行身份验证:
python 复制代码
@socketio.on('message')
@login_required
def handle_message(message):
    emit('reply', f"{current_user.id} says: {message}")
  1. 简单的登录页面 (templates/login.html):
html 复制代码
<!DOCTYPE html>
<html>
<head>
    <title>Login</title>
</head>
<body>
<form method="post">
    Username: <input type="text" name="username"><br>
    Password: <input type="password" name="password"><br>
    <input type="submit" value="Login">
</form>
</body>
</html>
  1. 简单的首页 (templates/index.html):

创建一个简单的首页 (index.html),用户登录后可以发送消息到服务器,然后接收服务器的响应。

index.html:

html 复制代码
<!DOCTYPE html>
<html>
<head>
    <title>SocketIO Chat</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
    <script type="text/javascript">
        let socket = io.connect('http://' + document.domain + ':' + location.port);

        socket.on('connect', function() {
            console.log('Connected!');
        });

        socket.on('reply', function(data) {
            document.getElementById('messages').innerText += data + '\n';
        });

        function sendMessage() {
            const input = document.getElementById('message_input');
            socket.emit('message', input.value);
            input.value = '';
        }
    </script>
</head>
<body>
    <h2>Welcome, Chat with SocketIO</h2>
    <textarea id="messages" cols="50" rows="10" readonly></textarea><br>
    <input type="text" id="message_input" placeholder="Type your message here...">
    <button onclick="sendMessage()">Send</button><br>
    <a href="{{ url_for('logout') }}">Logout</a>
</body>
</html>

此页面使用 Socket.IO 客户端库与服务器建立连接。当用户输入消息并点击"Send"按钮时,消息将被发送到服务器。服务器的响应将被添加到文本框中。

现在,回到我们的 Flask 代码,确保有一个返回 index.html 的路由:

python 复制代码
@app.route('/')
@login_required
def index():
    return render_template('index.html')

这样,当用户登录后,他们将被重定向到此首页,并可以与服务器通过 WebSocket 进行交互。

当然,要使这一切工作,还需要在 Flask 环境中适当地设置和运行所有内容。可能需要处理任何跨域问题(如果它们存在的话),例如使用 Flask-CORS。

  1. 启动应用:
python 复制代码
if __name__ == '__main__':
    socketio.run(app, debug=True)

在这个简单示例中,我们首先定义了一个用于用户身份验证的 Flask 登录路由。然后,我们为 SocketIO 定义了一个处理消息的事件,它使用 @login_required 装饰器确保只有已登录的用户才能发送消息。

相关推荐
小小张说故事4 分钟前
Python 的 dict 为什么插入顺序不会乱?拆开 3.6 的紧凑布局:indices 与 entries 两张表
python
椰萝Yerosius5 分钟前
严正声明 | 博主已正式放弃CSDN作为博客平台
python
利威尔xu14 分钟前
Go GMP 调度器 10 个高频追问:3 个线上故障让 P99 从 80ms 飙到 2s、10 万 goroutine 泄漏
开发语言·后端·面试·性能优化·golang
肖永威21 分钟前
python版微电网仿真工具的前端托管选型:从http.server到FastAPI StaticFiles
前端·python·http·fastapi
梦影_23 分钟前
MySQL进阶教程(二)—— 储存过程与触发器(下)
开发语言·数据库·后端·sql·mysql·oracle·数据库开发
IT_陈寒24 分钟前
为什么你应该学习Java?
前端·人工智能·后端
AINative软件工程27 分钟前
LLM 应用的 Read-Your-Writes 一致性工程实践:写完就读,模型却返回旧数据
后端
lg_cool_29 分钟前
Python 代码打包
开发语言·python
2601_9628857240 分钟前
如何用 Python 做 MACD 金叉全市场选股?
开发语言·python
FfHUCisI42 分钟前
无锁 Reactor 网络模型与 gnet / evio 架构拆解
服务器·开发语言·后端·golang