57 lines
1.8 KiB
Python
57 lines
1.8 KiB
Python
from flask import Flask, request, jsonify, g
|
|
from flask_sqlalchemy import SQLAlchemy
|
|
from database import init_db
|
|
from models import db, Game
|
|
from user_management import user_bp, authenticate
|
|
import os
|
|
from datetime import datetime
|
|
|
|
app = Flask(__name__)
|
|
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(app.instance_path, 'games.db')
|
|
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
|
|
db.init_app(app)
|
|
|
|
# Stelle sicher, dass der instance-Ordner existiert
|
|
os.makedirs(app.instance_path, exist_ok=True)
|
|
|
|
with app.app_context():
|
|
init_db() # Ensure the database is initialized before any operations
|
|
|
|
@app.route('/games', methods=['POST'])
|
|
def add_game():
|
|
if not authenticate():
|
|
return jsonify({'message': 'Unauthorized access!'}), 401
|
|
data = request.json
|
|
buyer_username = g.user.username # Get the username from the authenticated user
|
|
new_game = Game(
|
|
image=data['image'],
|
|
title=data['title'],
|
|
date=datetime.now().strftime('%Y-%m-%d'), # Set current date
|
|
buyer=buyer_username, # Set buyer as the authenticated user's username
|
|
owned=data['owned']
|
|
)
|
|
db.session.add(new_game)
|
|
db.session.commit()
|
|
return jsonify({'message': 'Game added!'}), 201
|
|
|
|
@app.route('/games', methods=['GET'])
|
|
def get_games():
|
|
if not authenticate():
|
|
return jsonify({'message': 'Unauthorized access!'}), 401
|
|
games = Game.query.all()
|
|
return jsonify([{
|
|
'id': game.id,
|
|
'image': game.image,
|
|
'title': game.title,
|
|
'date': game.date,
|
|
'buyer': game.buyer,
|
|
'owned': game.owned
|
|
} for game in games])
|
|
|
|
app.register_blueprint(user_bp) # Register the user management blueprint
|
|
|
|
if __name__ == '__main__':
|
|
with app.app_context():
|
|
init_db() # Ensure the database is initialized when the app starts
|
|
app.run(debug=True)
|