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

相关推荐
kobe_OKOK_3 小时前
DRF接口幂等操作
python·django
SomeB1oody3 小时前
【RustyML入门】6.3. 并行归约
开发语言·后端·机器学习·rust·教程
廿士4 小时前
python脚本使用相关
python
青 春 记 忆4 小时前
零基础入门python19:Flask账本第一步——应用工厂、蓝图和健康检查
python·flask·后端开发
朦胧之4 小时前
Python 后端核心知识
python
Profile排查笔记4 小时前
指纹浏览器哪个好?从 Profile、代理、权限和自动化能力判断是否适合
前端·人工智能·后端·自动化
用户938515635074 小时前
用 AI 结对编程从 0 搭一个"单词后台管理系统":Next.js + Supabase + Drizzle + shadcn/ui 全记录
后端·postgresql·next.js
denggun123455 小时前
yield
前端·数据库·python
爱学习的小邓同学5 小时前
Golang --- (1)第一个Golang程序
开发语言·后端·golang
zx_741484816 小时前
【Python 入门】面向对象基础:类、对象、成员变量与构造方法
开发语言·python