按照 Flask 教程 未创建我的数据库:
main.py:
from website import create_app
app = create_app()
if __name__ == '__main__':
app.run(debug=True)
__init__.py:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from os import path
db = SQLAlchemy()
DB_NAME = "database.db"
def create_app():
app = Flask(__name__)
app.secret_key = 'hjshjhdjah kjshkjdhjs'
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, Note
with app.app_context():
db.create_all()
return app
auth.py:
from flask import Blueprint, render_template, request, flash, redirect, url_for
from .models import User
from werkzeug.security import generate_password_hash, check_password_hash
from . import db
auth = Blueprint('auth', __name__)
@auth.route('/login', methods=['GET', 'POST'])
def login():
return render_template("login.html")
@auth.route('/logout')
def logout():
return "<p>under construction</p>"
@auth.route('/signup', methods=['GET', 'POST'])
def signup():
if request.method == 'POST':
email = request.form.get('email')
firstName = request.form.get('firstname')
lastName = request.form.get('lastname')
password1 = request.form.get('password1')
password2 = request.form.get('password2')
if password1 != password2:
flash('Password does not match.', category='error')
elif len(password1) < 8:
flash('Password must contain 8 characters.', category='error')
elif len(firstName) < 3:
flash('First name is too short.', category='error')
elif len(lastName) < 2:
flash('Last name name is too short.', category='error')
elif len(email) < 5:
flash('Email is invalid.', category='error')
else:
new_user = User(email=email, first_name=firstName, last_name=lastName, password=generate_password_hash(
password1, method='scrypt'))
db.session.add(new_user)
db.session.commit()
flash('Account created!', category='success')
return redirect(url_for('views.home'))
return render_template("signup.html")
models.py:
from . import db
from flask_login import UserMixin
from sqlalchemy.sql import func
class Note(db.Model):
id = db.Column(db.Integer, primary_key=True)
data = db.Column(db.String(10000))
date = db.Column(db.DateTime(timezone=True), default=func.now())
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
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))
last_name = db.Column(db.String(150))
notes = db.relationship('Note')
views。 py:
from flask import Blueprint, render_template
views = Blueprint('views', __name__)
@views.route('/')
def home():
return render_template("home.html")
创建数据库的函数:
__init__.py:
from .models import User, Note
create_database(app)
return app
def create_database(app):
if not path.exists('website/' + DB_NAME):
db.create_all()
print('Created Database!')
我将其更改为:
from .models import User, Note
with app.app_context():
db.create_all()
return app
它对其他人有用。
你遇到的问题在于数据库创建逻辑在 Flask 应用的工厂函数之外被调用。
问题所在:
在你最初的代码中,
create_database
函数是在
create_app
函数
之后
定义和调用的。这意味着,当你的应用启动并运行
create_app
时,
create_database
函数还没有被定义,因此数据库没有被创建。
解决方法:
你已经做出了正确的修改!将
db.create_all()
包裹在
with app.app_context():
中并将其放置在
create_app
函数内部是正确的做法。这样可以确保:
-
应用上下文:
with app.app_context():
语句创建了一个应用上下文,这对于 Flask-SQLAlchemy 正确初始化和与你的应用交互是必要的。 -
调用时机:
将
db.create_all()
放在create_app
函数内部可以确保在应用启动时创建数据库。
改进后的代码:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from os import path
db = SQLAlchemy()
DB_NAME = "database.db"
def create_app():
app = Flask(__name__)
app.secret_key = 'hjshjhdjah kjshkjdhjs'
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, Note
# 在应用上下文和 create_app 函数内部创建数据库
with app.app_context():
db.create_all()
# 可选:添加打印语句以确认数据库已创建
print('Created Database!')
return app
通过这个修改,你的数据库应该会在每次应用启动时自动创建。
标签:python,sqlite,flask,flask-sqlalchemy From: 78801039