From 56f8939b9dbdfd8e022ecdfe1ef5600f79162154 Mon Sep 17 00:00:00 2001 From: "Manuel Weiser (aider)" Date: Tue, 3 Sep 2024 12:05:54 +0200 Subject: [PATCH] feat: send base64 encoded images in game list response --- game_collection/app.py | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/game_collection/app.py b/game_collection/app.py index e321a9d..d5cef03 100644 --- a/game_collection/app.py +++ b/game_collection/app.py @@ -7,6 +7,7 @@ import os from datetime import datetime import requests from bs4 import BeautifulSoup +import base64 app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(app.instance_path, 'games.db') @@ -20,6 +21,10 @@ os.makedirs(os.path.join(app.instance_path, 'game_images'), exist_ok=True) # Cr with app.app_context(): init_db() # Ensure the database is initialized before any operations +def encode_image_to_base64(image_path): + with open(image_path, "rb") as image_file: + return base64.b64encode(image_file.read()).decode('utf-8') + @app.route('/games', methods=['POST']) def add_game(): if not authenticate(): @@ -54,14 +59,19 @@ 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]) + games_list = [] + for game in games: + image_path = os.path.join(app.instance_path, game.image) + image_base64 = encode_image_to_base64(image_path) if os.path.exists(image_path) else None + games_list.append({ + 'id': game.id, + 'image': image_base64, # Base64 encoded image + 'title': game.title, + 'date': game.date, + 'buyer': game.buyer, + 'owned': game.owned + }) + return jsonify(games_list) @app.route('/games/search', methods=['GET']) def search_game_api():