I have a discord.py bot that has an avatar history command. When a user updates their avatar on discord, it keeps a record of it in a PostgreSQL database. The avatar history command generates a link that when clicked, takes you to my API and shows HD/Animated version of all of the avatars for that user.
For my user, I have about 130 in the database and it loads fine, but for one bot, there are about 600 pictures in the database for this bot. When you try to load the api link, it loads for about 30 seconds and then it goes to a 502 Bad Gateway page.
Where might the issue be, and how can i fix this issue?
My process works, so I want to keep the process the same if possible, but also optimize it if possible.
Here is the API code
api.py
@waywardapi.get("/avatarhistory/{user_id}", response_class=HTMLResponse)
async def get_avatar_image(user_id: int, request: Request, temp_ref_id: Optional[str] = Query(None, alias="reference_id")):
async with pool.acquire() as conn:
avatar_rows = await conn.fetch(
"SELECT avatar_data, format, user_name FROM scrap_avatar_history WHERE user_id = $1 ORDER BY timestamp DESC",
user_id
)
avatars = []
for row in avatar_rows:
avatar_data = row['avatar_data']
file_format = row['format']
username = row['user_name']
is_animated = file_format == 'gif'
avatar = {
'image_data': avatar_data,
'is_animated': is_animated,
'username': username
}
avatars.append(avatar)
if avatars:
img_bytes_value = avatars[0]['image_data']
return templates.TemplateResponse("avatar.html", {"request": request, "avatars": avatars, "image_data": img_bytes_value})```
HTML
avatar.html
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>{{ avatars[0].username }}'s Avatar History</title>
{% if avatars %}
<link rel="icon" type="image/png" href="data:image/png;base64,{{ avatars[0].image_data|b64encode }}">
{% endif %}
<!-- <link rel="icon" type="image/x-icon" href="/favicon.ico"> -->
<!-- <link href="css/avs.css" rel="stylesheet"> -->
</head>
<body>
<div class="myGallery">
{% for avatar in avatars %}
{% if not avatar.is_animated %}
<img src="data:image/png;base64,{{ avatar.image_data|b64encode }}" width="184.5" height="184.5" class="avatar-image" alt="animated avatar">
{% else %}
<img src="data:image/gif;base64,{{ avatar.image_data|b64encode }}" width="184.5" height="184.5" class="avatar-image" alt="avatar">
{% endif %}
{% endfor %}
</div>
</body>
</html>