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

相关推荐
巴里巴气1 分钟前
selenium基础知识 和 模拟登录selenium版本
爬虫·python·selenium·爬虫模拟登录
19895 分钟前
【零基础学AI】第26讲:循环神经网络(RNN)与LSTM - 文本生成
人工智能·python·rnn·神经网络·机器学习·tensorflow·lstm
martinzh11 分钟前
Spring AI 项目介绍
后端
JavaEdge在掘金11 分钟前
Redis 数据倾斜?别慌!从成因到解决方案,一文帮你搞定
python
ansurfen15 分钟前
我的第一个AI项目:从零搭建RAG知识库的踩坑之旅
python·llm
前端付豪20 分钟前
20、用 Python + API 打造终端天气预报工具(支持城市查询、天气图标、美化输出🧊
后端·python
爱学习的小学渣22 分钟前
关系型数据库
后端
武子康25 分钟前
大数据-33 HBase 整体架构 HMaster HRegion
大数据·后端·hbase
前端付豪26 分钟前
19、用 Python + OpenAI 构建一个命令行 AI 问答助手
后端·python
凌览26 分钟前
斩获 27k Star,一款开源的网站统计工具
前端·javascript·后端