使用flask初始化数据库

2024-04-24 22:56:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码:

init.py:

"""Initialize app."""
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()


def create_app():
    """Construct the core application."""
    app = Flask(__name__, instance_relative_config=False)

    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'

    app.config['RECAPTCHA_PUBLIC_KEY'] = '6LcmEeoUAAAAAIbdhgkFBvz676UCRJMjnSx8H6zy'
    app.config['RECAPTCHA_PARAMETERS'] = {'size': '100%'}

    db.init_app(app)

    # blueprint for auth routes in our app
    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint)

    # blueprint for non-auth parts of app
    from .__main__ import main as main_blueprint
    app.register_blueprint(main_blueprint)

    with app.app_context():
        # Import parts of our application
        from . import routes

        return app

我尝试用以下代码初始化数据库:

from realProject import db, create_app
db.create_all(app=create_app())

所有脚本都在realProject文件夹中 但在尝试编译最后一段代码时,我遇到以下错误:

ModuleNotFoundError: No module named 'realProject'

我做错了什么


Tags: 代码fromimportauthconfigappflaskdb
1条回答
网友
1楼 · 发布于 2024-04-24 22:56:35

您需要遵循以下结构:

|__project_name 
     |__app.py                         > The main file from where you run your app 
     |__app       -> This is the app folder
        ├── templates
        │   └── index.html
        └── __init__.py                  -> The __init__.py should be inside the app folder for it to be imported
        └── routes.py

然后在主文件中执行以下操作:

from app import db, create_app

db.create_all(app=create_app())

相关问题 更多 >