Python Flask蓝图使用

使用示例:

user.py

python 复制代码
from utils.sql import supabase
from flask import Blueprint,request, session
from utils.entity import r
user_bp = Blueprint('user', __name__, url_prefix='/user')

"""----------------------------------------
                API: 用户登录
-------------------------------------------"""
@user_bp.route('/login', methods=['POST'])
def user_login():
    reqJSONData = request.get_json(silent=True)

    if not reqJSONData: return r(code=401, msg='注册失败, 请求参数为空')
    username = reqJSONData.get('username')
    password = reqJSONData.get('password')

    if not all([username, password]):
        return r(code=401, msg='登录, 缺少请求参数')

    user = supabase.table('sys_user').select('*').eq('username',username).eq('password',password).execute().data
    # 4. 用户不存在, 直接返回
    if not user:
        return r(code=404, msg='用户名或密码错误')
    else:
        session['user_info'] = user
        return r(msg='登录成功', data=user)

@user_bp.route('/list', methods=['POST','get'])
def userList():
    user = supabase.table('sys_user').select('*').execute().data
    return user

app.py(也就是主文件)

python 复制代码
from flask import Flask
from flask_cors import CORS
from utils.entity import r

from api.user.user import user_bp
# 创建 Flask 实例
app = Flask(__name__)
app.register_blueprint(user_bp)

CORS(app, supports_credentials=True,resources=r'/*')

@app.route('/', methods=['GET'])
def hello():
    return r(code=200, msg='服务器访问成功!')

if __name__ == '__main__':
    app.run()

总结:

在单文件中创建蓝图:user_bp = Blueprint('user', name, url_prefix='/user')

在主文件中注册蓝图:app.register_blueprint(user_bp)

注意:

  1. 主文件中需要引入一下创建的蓝图
  2. 在app.run之前注册蓝图
相关推荐
千寻girling2 小时前
一份不可多得的 《 Django 》 零基础入门教程
后端·python·面试
stark张宇2 小时前
构建第一个AI聊天机器人:Flask+DeepSeek+Postgres实战
人工智能·postgresql·flask
databook5 小时前
探索视觉的边界:用 Manim 重现有趣的知觉错觉
python·动效
明月_清风7 小时前
Python 性能微观世界:列表推导式 vs for 循环
后端·python
明月_清风7 小时前
Python 性能翻身仗:从 O(n) 到 O(1) 的工程实践
后端·python
helloweilei1 天前
python 抽象基类
python
用户8356290780511 天前
Python 实现 PPT 转 HTML
后端·python
zone77391 天前
004:RAG 入门-LangChain读取PDF
后端·python·面试
zone77391 天前
005:RAG 入门-LangChain读取表格数据
后端·python·agent
树獭非懒2 天前
AI大模型小白手册|Embedding 与向量数据库
后端·python·llm