Compare commits

...

2 Commits

Author SHA1 Message Date
e7e70daec0 funktionierendes Grundprojekt 2024-08-05 20:43:29 +02:00
1231787e08 Datenbank Model ausgelagert 2024-08-05 17:48:09 +02:00
11 changed files with 71 additions and 70 deletions

30
app.py
View File

@ -1,30 +0,0 @@
from flask import Flask, render_template, request, jsonify
from flask_sqlalchemy import SQLAlchemy
# Initialize the database object
db = SQLAlchemy()
def create_app():
# Create a new Flask application instance
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
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# Initialize the database object with the Flask application instance
db.init_app(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
if __name__ == '__main__':
# Create and run the Flask application instance with debugging enabled
app = create_app()
app.run(debug=True)

View File

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

View File

@ -0,0 +1,9 @@
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///learn.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
import lernplattform.routes

6
lernplattform/app.py Normal file
View File

@ -0,0 +1,6 @@
from lernplattform import app
from lernplattform.models import initialize_database
if __name__ == '__main__':
initialize_database() # Initialisiere die Datenbank beim Start der Anwendung
app.run(debug=True)

16
lernplattform/models.py Normal file
View File

@ -0,0 +1,16 @@
from lernplattform import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
password = db.Column(db.String(60), nullable=False)
def __repr__(self):
return f"User('{self.username}', '{self.email}')"
def initialize_database():
from lernplattform import app
with app.app_context():
db.create_all()
print("Database and tables created successfully.")

21
lernplattform/routes.py Normal file
View File

@ -0,0 +1,21 @@
from flask import render_template, url_for, flash, redirect, jsonify
from lernplattform import app
from lernplattform.models import User
@app.route('/')
def index():
# Render the main page with the list of users
return render_template('index.html')
@app.route('/users', methods=['GET'])
def get_users():
users = User.query.all()
return jsonify([user.username for user in users])
@app.route('/users', methods=['POST'])
def create_user():
data = request.get_json()
new_user = User(username=data['username'], email=data['email'])
db.session.add(new_user)
db.session.commit()
return jsonify({'message': 'User created'}), 201

15
lernplattform/setup.py Normal file
View File

@ -0,0 +1,15 @@
from setuptools import setup, find_packages
VERSION = '0.0.1'
setup(
name='lernplattform',
version=VERSION,
license='MIT',
description='Eine Plattform zum lernen nach dem Leitner System',
author='Manuel Weiser',
author_email='manuel.weiser@me.com',
url='https://gitlab.fire-devils.org/ManuelW/Lerndatenbank',
packages=find_packages(exclude=('tests', 'docs', instance, env, _idee, __pycache__, templates)),
python_requires='>=3.10'
)

4
lernplattform/wsgi.py Normal file
View File

@ -0,0 +1,4 @@
from lernplattform import app
if __name__ == "__main__":
app.run()

View File

@ -1,7 +0,0 @@
from app import db
class User(db.Model):
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)

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')