Refactor app initialization: encapsulate Flask app setup and database initialization within a create_app function, improving modularity and error handling during startup.
This commit is contained in:
@@ -6,15 +6,33 @@ from flask_sqlalchemy import SQLAlchemy
|
||||
from werkzeug.security import generate_password_hash, check_password_hash
|
||||
import json
|
||||
|
||||
app = Flask(__name__)
|
||||
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', 'default-dev-key')
|
||||
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///mindmap.db'
|
||||
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
|
||||
|
||||
db = SQLAlchemy(app)
|
||||
login_manager = LoginManager(app)
|
||||
db = SQLAlchemy()
|
||||
login_manager = LoginManager()
|
||||
login_manager.login_view = 'login'
|
||||
|
||||
def create_app():
|
||||
app = Flask(__name__)
|
||||
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', 'default-dev-key')
|
||||
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///mindmap.db'
|
||||
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
|
||||
|
||||
db.init_app(app)
|
||||
login_manager.init_app(app)
|
||||
|
||||
with app.app_context():
|
||||
# Initialize database and create root node
|
||||
db.create_all()
|
||||
try:
|
||||
root = MindMapNode.query.filter_by(parent_id=None).first()
|
||||
if not root:
|
||||
root = MindMapNode(name="Wissenschaft")
|
||||
db.session.add(root)
|
||||
db.session.commit()
|
||||
except Exception as e:
|
||||
print(f"Error initializing database: {str(e)}")
|
||||
|
||||
return app
|
||||
|
||||
# Database Models
|
||||
class User(UserMixin, db.Model):
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
@@ -276,27 +294,6 @@ def admin():
|
||||
|
||||
return render_template('admin.html', users=users, nodes=nodes, thoughts=thoughts)
|
||||
|
||||
@app.before_first_request
|
||||
def initialize_database():
|
||||
db.create_all()
|
||||
# Create root node if it doesn't exist
|
||||
if not MindMapNode.query.first():
|
||||
root = MindMapNode(name="Wissenschaft")
|
||||
db.session.add(root)
|
||||
db.session.commit()
|
||||
|
||||
# Flask starten
|
||||
if __name__ == '__main__':
|
||||
with app.app_context():
|
||||
# Initialize database and create root node
|
||||
db.create_all()
|
||||
try:
|
||||
root = MindMapNode.query.filter_by(parent_id=None).first()
|
||||
if not root:
|
||||
root = MindMapNode(name="Wissenschaft")
|
||||
db.session.add(root)
|
||||
db.session.commit()
|
||||
except Exception as e:
|
||||
print(f"Error initializing database: {str(e)}")
|
||||
|
||||
app = create_app()
|
||||
app.run(host="0.0.0.0", port=6000, debug=True)
|
||||
Reference in New Issue
Block a user