I develop a simple Flask app and reform the project following the package structure. Everything works fine before the the reforming. I create the database and table in python shell.
After the reforming, I come into a problem that the database is created but the table not. So when I try to add a user, the table not found error pops up.
The app structure is:
The init.py of the app:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from MyService.config import Config
db = SQLAlchemy()
def create_app():
app = Flask(__name__)
app.config.from_object(Config)
db.init_app(app)
with app.app_context():
db.create_all()
from MyService.users.routes import users
from MyService.admin.routes import admin
app.register_blueprint(users)
app.register_blueprint(admin)
return app
The config.py class:
class Config:
SECRET_KEY = "oxdte0UGTV0vSpQoxqTZg7kPjGQWaQzi"
SQLALCHEMY_DATABASE_URI = 'sqlite:///users.sqlite3'
SQLALCHEMY_TRACK_MODIFICATIONS = False
The function that add a new user to the database:
@admin.route('/login', methods=["POST", "GET"])
def login():
if request.method == "POST":
user = request.form["nm"]
session["user"] = user
if User.query.filter_by(name=user).first():
session["email"] = User.query.filter_by(name=usr).first().email
else:
usr = User(user, "")
db.session.add(usr)
db.session.commit()
return redirect(url_for("users.user"))
else:
if "user" in session:
return redirect(url_for("users.user"))
return render_template("login.html")
The run.py file:
from MyService import create_app
app=create_app()
if __name__ == '__main__':
app.run(debug=True)
As you can see in the folder structure, there is a instance folder with the users.sqlite3 database file. The folder and the file are all automatically created after running the app. But I do not know why the table is not created. The error I meet is:
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: users
[SQL: SELECT users._id AS users__id, users.name AS users_name, users.email AS users_email
FROM users
WHERE users.name = ?
LIMIT ? OFFSET ?]
[parameters: ('add', 1, 0)]
(Background on this error at: https://sqlalche.me/e/20/e3q8)
Could someone help me with that? Thank you