Datenbank Model ausgelagert

This commit is contained in:
Manuel Weiser 2024-08-05 17:48:09 +02:00
parent b2b5bd9770
commit 1231787e08
4 changed files with 35 additions and 52 deletions

35
app.py
View File

@ -1,29 +1,36 @@
from flask import Flask, render_template, request, jsonify
from flask_sqlalchemy import SQLAlchemy
# Initialize the database object
db = SQLAlchemy()
# Importing db from models to ensure it exists and is initialized properly
from models import db
# Function to initialize the database with the app context
def initialize_db(app):
# Push the application context to make it available within this function
app.app_context().push()
# Initialize the SQLAlchemy database with the Flask app configuration
db.init_app(app)
# Create all tables defined in the models (if they don't already exist)
db.create_all()
# Commit any changes to the database session
db.session.commit()
# Function to create and configure the Flask application
def create_app():
# Create a new Flask application instance
# Create a new Flask application instance with the name of the current module (__name__)
app = Flask(__name__)
# Configure the SQLite database URI for the application
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///mydatabase.db'
# Disable tracking modifications to SQLAlchemy objects
# Configure the SQLAlchemy database URI for SQLite, using 'learn.db' as the file location
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///learn.db'
# Disable tracking modifications of objects in the session to improve performance
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# Initialize the database object with the Flask application instance
db.init_app(app)
# Call the initialize_db function with the newly created Flask app instance
initialize_db(app)
# Import and initialize models, then create tables within the app context
with app.app_context():
from models import User # Assuming there is a file named models.py containing the User model
from utils import check_and_create_tables # Assuming there is a file named utils.py containing the check_and_create_tables function
check_and_create_tables(db) # Call the function to ensure tables are created if they don't exist
return app
# Entry point for running the Flask application when this script is executed directly
if __name__ == '__main__':
# Create and run the Flask application instance with debugging enabled
app = create_app()

View File

@ -1,3 +0,0 @@
class Config:
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///learn.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

View File

@ -1,7 +1,16 @@
from app import db
# Import necessary modules
from flask_sqlalchemy import SQLAlchemy
class User(db.Model):
# Create an instance of SQLAlchemy and assign it to db
db = SQLAlchemy()
# Define a User model class that inherits from db.Model
class table_user(db.Model):
# Define the id column as an integer primary key
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
password = db.Column(db.String(120), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
# Define the user_name column as a string with max length 80 and must be unique and not nullable
user_name = db.Column(db.String(80), unique=True, nullable=False)
# Define the user_password column as a string with max length 120 and must be unique and not nullable
user_password = db.Column(db.String(120), unique=True, nullable=False)
# Define the user_email column as a string with max length 120 and must be unique and not nullable
user_email = db.Column(db.String(120), unique=True, nullable=False)

View File

@ -1,30 +0,0 @@
from sqlalchemy import inspect, Integer, String
def check_and_create_tables(db):
inspector = inspect(db.engine)
# Überprüfen, ob die Tabelle 'user' existiert
if not inspector.has_table('user'):
print("Tabelle 'user' existiert nicht, sie wird erstellt.")
db.create_all()
else:
print("Tabelle 'user' existiert.")
# Überprüfen der Spalten
columns = inspector.get_columns('user')
column_names = [col['name'] for col in columns]
# Benötigte Spalten
required_columns = {
'id': Integer,
'username': String,
'email': String
}
for col_name, col_type in required_columns.items():
if col_name not in column_names:
print(f"Spalte '{col_name}' fehlt, sie wird hinzugefügt.")
with db.engine.connect() as conn:
if col_type == Integer:
conn.execute(f'ALTER TABLE user ADD COLUMN {col_name} INTEGER')
elif col_type == String:
conn.execute(f'ALTER TABLE user ADD COLUMN {col_name} STRING')