modified: app.py

This commit is contained in:
SimolZimol
2024-10-31 18:02:08 +01:00
parent 8fc2e3bf56
commit a60052b361

46
app.py
View File

@@ -34,9 +34,11 @@ DISCORD_TOKEN_URL = "https://discord.com/api/oauth2/token"
DISCORD_API_URL = "https://discord.com/api/users/@me"
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
# Redis-Verbindung
redis_url = "redis://:Uo28JDAlM3LiwjKyaOgyt08PCjJUKsW8dFKrcmZn3jN2TF074dNkFnQoSpyLo8WL@skgwsss0wc8040o4sgg044gs:6379/0"
r = redis.Redis.from_url(redis_url)
# Verzeichnis für Profilbilder
PROFILE_IMAGE_DIR = 'static/profile_images'
os.makedirs(PROFILE_IMAGE_DIR, exist_ok=True)
@@ -68,14 +70,22 @@ def stop_bot():
print("Bot läuft nicht.")
def get_db_connection():
"""Stellt eine Verbindung zur MySQL-Datenbank her."""
return mysql.connector.connect(
host=DB_HOST,
port=DB_PORT,
user=DB_USER,
password=DB_PASS,
database=DB_NAME
)
"""Stellt eine Verbindung zur MySQL-Datenbank her und aktiviert die automatische Wiederverbindung."""
try:
connection = mysql.connector.connect(
host=DB_HOST,
port=DB_PORT,
user=DB_USER,
password=DB_PASS,
database=DB_NAME,
connection_timeout=300, # Timeout auf 300 Sekunden setzen
autocommit=True
)
connection.reconnect(attempts=3, delay=5) # Versuche die Verbindung dreimal wiederherzustellen, mit 5 Sekunden Abstand
return connection
except mysql.connector.Error as e:
print(f"Database error: {e}")
return None
def token_updater(token):
session['oauth_token'] = token
@@ -99,33 +109,38 @@ def fetch_and_cache_profile_picture(user_id, avatar_url):
"""Lädt das Profilbild herunter und speichert es lokal und in Redis."""
if not user_id or not avatar_url:
# Fallback auf ein Standardprofilbild, wenn keine gültigen Werte vorhanden sind
print(f"Skipping user {user_id}: Missing avatar URL.")
return "/static/default_profile.png"
local_image_path = os.path.join(PROFILE_IMAGE_DIR, f"{user_id}.png")
# Checken, ob das Bild schon lokal vorhanden ist
# Prüfen, ob das Bild bereits lokal gespeichert ist
if os.path.exists(local_image_path):
r.set(str(user_id), local_image_path) # Sicherstellen, dass der Key ein String ist
print(f"Profile picture for user {user_id} already exists locally.")
r.set(str(user_id), local_image_path)
return local_image_path
try:
# Bild von Discord herunterladen und speichern
response = requests.get(avatar_url)
# Bild von der URL herunterladen und speichern
response = requests.get(avatar_url, timeout=10)
response.raise_for_status()
with open(local_image_path, 'wb') as img_file:
img_file.write(response.content)
# Pfad in Redis speichern
r.set(str(user_id), local_image_path) # Konvertiere user_id zu einem String
r.set(str(user_id), local_image_path)
print(f"Profile picture for user {user_id} downloaded and cached.")
return local_image_path
except requests.RequestException as e:
print(f"Error fetching profile picture for user {user_id}: {e}")
return "/static/default_profile.png" # Standardbild verwenden
return "/static/default_profile.png"
def get_profile_picture(user_id, avatar_url):
"""Gibt den Pfad zum Profilbild eines Benutzers zurück, entweder aus Redis oder durch Abruf."""
cached_image = r.get(user_id)
cached_image = r.get(str(user_id))
if cached_image:
return cached_image.decode('utf-8') # Rückgabe des Pfads aus Redis
return fetch_and_cache_profile_picture(user_id, avatar_url)
@@ -136,7 +151,6 @@ def utility_processor():
return fetch_and_cache_profile_picture(user_id, avatar_url)
return dict(get_profile_picture=get_profile_picture)
@app.route("/update_all_profile_pictures")
def update_all_profile_pictures():
"""Aktualisiert alle Profilbilder der Benutzer."""