Flask-导入错误:无法导入名称数据库

时间:2018-11-16 12:02:30

标签: python python-3.x flask flask-sqlalchemy

从初始化文件导入db时出现问题。我已经在文件夹中设置了几个初始化文件的蓝图。

可能是什么原因?

这是我的 init .py文件,该文件位于第一个文件夹内,其中还有其他几个文件夹及其各自的蓝图。

from flask import Flask
from flask_apscheduler import APScheduler
from importlib import import_module
from hvac import Client as VaultClient
from flask_login import LoginManager
from flask_sqlalchemy import SQLAlchemy
from tClinix.base.default import create_default_user

# for the tests, we set expire_on_commit to false
db = SQLAlchemy(session_options={"expire_on_commit": False})
login_manager = LoginManager()
scheduler = APScheduler()

from tClinix.admin.models import User

def create_vault_client(app):
    return VaultClient(
        url=app.config['VAULT_ADDR'],
        token=app.config['VAULT_TOKEN']
    )

def register_extensions(app):
    db.init_app(app)
    login_manager.init_app(app)
    if not scheduler.running:
        scheduler.init_app(app)
        scheduler.start()

def register_blueprints(app):
    blueprints = (
        'base',
        'admin', 
    )
    for blueprint in blueprints:
        module = import_module(f'tClinix.{blueprint}')
        app.register_blueprint(module.blueprint)
        print("===> blueprint for {} registered".format(blueprint))

def configure_login_manager(app):
    @login_manager.user_loader
    def user_loader(id):
        return db.session.query(User).filter_by(id=id).first()

    @login_manager.request_loader
    def request_loader(request):
        name = request.form.get('name')
    user = db.session.query(User).filter_by(name=name).first()
    return user if user else None

def configure_database(app):
    @app.teardown_request
    def shutdown_session(exception=None):
        db.session.remove()

    @app.before_first_request
    def create_default():
        db.create_all()
        create_default_user()

def create_app(path, config):
    app = Flask(__name__, static_folder='base/static')
    app.config.from_object(config)
    app.production = not app.config['DEBUG']
    app.path = path
    register_extensions(app)
    register_blueprints(app)
    configure_login_manager(app)
    configure_database(app)
    if app.production:
        app.vault_client = create_vault_client(app)
    return app

这是我的主要app.py文件

from flask_migrate import Migrate
from os import environ
from pathlib import Path
from sys import exit

from config import config_dict
from tClinix import  db, app

get_config_mode = environ.get('TCLINIX_CONFIG_MODE', 'Debug')
print("config mode = " + get_config_mode)
try:
    config_mode = config_dict[get_config_mode.capitalize()]
except KeyError:
    exit('Error: Invalid TCLINIX_CONFIG_MODE environment variable entry.')

app = create_app(Path.cwd(), config_mode)

Migrate(app, db) 

0 个答案:

没有答案