Lerndatenbank/lernplattform/routes.py

53 lines
1.9 KiB
Python
Raw Normal View History

2024-08-06 20:11:36 +02:00
from flask import render_template, url_for, flash, redirect, jsonify, request, session
2024-08-05 20:43:29 +02:00
from lernplattform import app
from lernplattform.models import User
from lernplattform import db
from lernplattform.classes import login
2024-08-05 20:43:29 +02:00
@app.route('/')
def index():
"""
Renders the main page of the application.
This function checks if a user is logged in by checking for a 'user_name' cookie.
If the user is logged in, it retrieves the username from the database using the cookie value.
If not, it defaults to 'Gast'. The main page is then rendered with the current username.
Returns:
A rendered HTML template with the current username.
"""
2024-08-06 20:11:36 +02:00
login.check(request.cookies.get('user_name'))
# Render the main page with the current username
2024-08-06 20:11:36 +02:00
return render_template('index.html', user_name=session['user_name'])
2024-08-05 20:43:29 +02:00
@app.route('/users', methods=['GET'])
def get_users():
# Query all users from the database
2024-08-05 20:43:29 +02:00
users = User.query.all()
# Create a list of dictionaries with user information
user_list = [
{
"id": user.id,
"username": user.username,
"email": user.email,
"password": user.password
}
for user in users
]
# Return the list of users as a JSON response
return jsonify(user_list)
#return user_list[0]['username']
2024-08-05 20:43:29 +02:00
@app.route('/users', methods=['POST'])
def create_user():
# Get the JSON data from the request body
2024-08-05 20:43:29 +02:00
data = request.get_json()
# Create a new User object with the provided username, email, and password
new_user = User(username=data['username'], email=data['email'], password=data['password'])
# Add the new user to the database session
2024-08-05 20:43:29 +02:00
db.session.add(new_user)
# Commit the transaction to save the new user in the database
2024-08-05 20:43:29 +02:00
db.session.commit()
# Return a success message with status code 201 (Created)
2024-08-05 20:43:29 +02:00
return jsonify({'message': 'User created'}), 201