Lerndatenbank/lernplattform/routes.py

53 lines
1.9 KiB
Python

from flask import render_template, url_for, flash, redirect, jsonify, request, session
from lernplattform import app
from lernplattform.models import User
from lernplattform import db
from lernplattform.classes import login
@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.
"""
login.check(request.cookies.get('user_name'))
# Render the main page with the current username
return render_template('index.html', user_name=session['user_name'])
@app.route('/users', methods=['GET'])
def get_users():
# Query all users from the database
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']
@app.route('/users', methods=['POST'])
def create_user():
# Get the JSON data from the request body
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
db.session.add(new_user)
# Commit the transaction to save the new user in the database
db.session.commit()
# Return a success message with status code 201 (Created)
return jsonify({'message': 'User created'}), 201