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 装饰器确保只有已登录的用户才能发送消息。

相关推荐
星星电灯猴3 分钟前
iOS 上架 H5 应用的可行性与实现路径,壳应用、合规要求与构建流程的技术分析
后端
qwepoilkjasd10 分钟前
订单事件消费者迁移方案 - 幂等性与可靠性设计
后端
用户23452670098238 分钟前
Python实现异步任务队列深度好文
后端·python
夫唯不争,故无尤也41 分钟前
PyTorch 的维度变形一站式入门
人工智能·pytorch·python
00后程序员1 小时前
如何防止 IPA 被反编译,从结构隐藏到符号混淆的多层防护方案
后端
熊猫钓鱼>_>1 小时前
从零开始构建RPG游戏战斗系统:实战心得与技术要点
开发语言·人工智能·经验分享·python·游戏·ai·qoder
SamDeepThinking1 小时前
在 MySQL 里,不建议使用长事务的根因
后端·mysql
文心快码BaiduComate1 小时前
用文心快码写个「隐私优先」的本地会议助手
前端·后端·程序员
BoBoZz191 小时前
TriangleStrip连续三角带
python·vtk·图形渲染·图形处理
生信大表哥1 小时前
Python单细胞分析-基于leiden算法的降维聚类
linux·python·算法·生信·数信院生信服务器·生信云服务器