如何将flask SQLAlchemy db导入到蓝图中?

问题描述 投票:0回答:1

我有一个带有模块的 Flaks 应用程序。我应该使用什么方法在蓝图中创建 SQLAlchemy 实例?我的init.py

from flask import Flask
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
from .config import PGHOST, PGUSER, PGPORT, PGDATABASE, PGPASSWORD
from .auth import auth_bp
from .user_ui import user_ui_bp



def create_app():
    app = Flask(__name__)
    CORS(app)
    app.config['SQLALCHEMY_DATABASE_URI'] = f"postgresql://{PGUSER}:{PGPASSWORD}@{PGHOST}:{PGPORT}/{PGDATABASE}"
    app.config['SECRET_KEY'] = "secret_key"
    db = SQLAlchemy(app)
    db.init_app(app)
    

    # Register Blueprints
    app.register_blueprint(auth_bp)
    app.register_blueprint(user_ui_bp)

    return app

my auth.py blueprint
import datetime
import jwt
import bcrypt
from flask import Blueprint, request, jsonify
from .db_utils import DbUser
from .config import SECRET_KEY

auth_bp = Blueprint('auth', __name__)

@auth_bp.route('/api/register', methods=["POST"])
def register():
    data = request.get_json()
    password = data['password'].encode('utf-8')

    # Hash the password
    hashed_password = bcrypt.hashpw(password, bcrypt.gensalt())

    user = DbUser(username=data['username'], password=hashed_password.decode('utf-8'))
    db.session.add(user)
    db.session.commit()
    return jsonify({'message': 'User registered successfully'}), 201


I need initiate db, but I have no idea where I should import it from. 
I am not even sure what approach I should be using.

我尝试在我的蓝图中启动 SQLAlchemy 的新实例

db = SQLAlchemy()

但最终出现“运行时错误:‘SQLAlchemy’实例已在此 Flask 应用程序上注册。请导入并使用该实例。” 我还尝试从应用程序导入数据库,但是“导入错误:无法从部分初始化的模块“应用程序”导入名称“数据库”(很可能是由于循环导入)” 也试过了

db = current_app.config['db']
但出现错误

RuntimeError: Working outside of application context.

This typically means that you attempted to use functionality that needed
the current application. To solve this, set up an application context
with app.app_context(). See the documentation for more information.

我觉得从当前应用程序获取上下文是最有意义的,但我不知道如何解决这个问题......

python flask flask-sqlalchemy
1个回答
0
投票

您应该尝试在方法之外初始化

db
create_app
:

from flask import Flask
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
from .config import PGHOST, PGUSER, PGPORT, PGDATABASE, PGPASSWORD
from .auth import auth_bp
from .user_ui import user_ui_bp



def create_app():
    app = Flask(__name__)
    CORS(app)
    app.config['SQLALCHEMY_DATABASE_URI'] = f"postgresql://{PGUSER}:{PGPASSWORD}@{PGHOST}:{PGPORT}/{PGDATABASE}"
    app.config['SECRET_KEY'] = "secret_key"        

    # Register Blueprints
    app.register_blueprint(auth_bp)
    app.register_blueprint(user_ui_bp)

    return app


app = create_app()

db = SQLAlchemy(app)
db.init_app(app)

您还可以仔细检查文档https://flask-sqlalchemy.palletsprojects.com/en/2.x/quickstart/

© www.soinside.com 2019 - 2024. All rights reserved.