feat: send base64 encoded images in game list response

This commit is contained in:
Manuel Weiser 2024-09-03 12:05:54 +02:00
parent e28d6660ae
commit 56f8939b9d

View File

@ -7,6 +7,7 @@ import os
from datetime import datetime from datetime import datetime
import requests import requests
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
import base64
app = Flask(__name__) app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(app.instance_path, 'games.db') 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(): with app.app_context():
init_db() # Ensure the database is initialized before any operations 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']) @app.route('/games', methods=['POST'])
def add_game(): def add_game():
if not authenticate(): if not authenticate():
@ -54,14 +59,19 @@ def get_games():
if not authenticate(): if not authenticate():
return jsonify({'message': 'Unauthorized access!'}), 401 return jsonify({'message': 'Unauthorized access!'}), 401
games = Game.query.all() games = Game.query.all()
return jsonify([{ games_list = []
'id': game.id, for game in games:
'image': game.image, image_path = os.path.join(app.instance_path, game.image)
'title': game.title, image_base64 = encode_image_to_base64(image_path) if os.path.exists(image_path) else None
'date': game.date, games_list.append({
'buyer': game.buyer, 'id': game.id,
'owned': game.owned 'image': image_base64, # Base64 encoded image
} for game in games]) 'title': game.title,
'date': game.date,
'buyer': game.buyer,
'owned': game.owned
})
return jsonify(games_list)
@app.route('/games/search', methods=['GET']) @app.route('/games/search', methods=['GET'])
def search_game_api(): def search_game_api():