Flask应用程序,db.create_all()不创建数据库

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

我是创建 Flask 应用程序的新手,我正在按照教程快速入门。我发现有关 db.create_all() 的问题很常见,但我不明白为什么我无法创建数据库。

my project structure

我正在 __ init __.py 中初始化数据集,如下所示:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()
DB_NAME = 'database.db'

def create_app():
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'uiasdasn moaisw eeert'
    app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{DB_NAME}'
    db.init_app(app)

    from .views import views
    from .auth import auth

    app.register_blueprint(views, url_prefix='/')
    app.register_blueprint(auth, url_prefix='/')

    from .models import User
    
    with app.app_context():
         db.create_all()
         db.session.commit()

    return app

而 User 类是在 models.py 中定义的

from . import db
from flask_login import UserMixin

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(150), unique=True)
    password = db.Column(db.String(150))
    first_name = db.Column(db.String(150))

你能告诉我我做错了什么吗?

python flask sqlalchemy
1个回答
0
投票

好吧,如果您显示完整的 init.py 文件,那么您就错过了执行该函数:)

您应该添加类似以下内容:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()
DB_NAME = 'database.db'

def create_app():
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'uiasdasn moaisw eeert'
    app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{DB_NAME}'
    db.init_app(app)

    from .views import views
    from .auth import auth

    app.register_blueprint(views, url_prefix='/')
    app.register_blueprint(auth, url_prefix='/')

    from .models import User
    
    with app.app_context():
         db.create_all()
         db.session.commit()

# What you should add:

app = create_app()

# ONLY FOR PRE!!!

if __name__ == "__main__":
        app.run(debug=True, port=3000)

我提供的内容中可能缺少其他内容,但可以肯定的是,您需要执行该函数,以便做好准备,功能

亲切的问候

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