In this post I am going to show a Flask application which takes an integer and searches the Magic the Gathering database for an image of a corresponding card whose “multiverse ID” is the same as the given number.
I used the requests package to get the image content. Supposing you get the content back, which will result in a response status code of 200, the image will still need to be converted into a memory binary stream. That’s where io.BytesIO comes in handy. Once the stream is prepared, the flask.send_file function can be used to prepare the rendered page content containing the file.
"""Flask application for displaying Magic: The Gathering card images."""
from io import BytesIO
import requests
from flask import Flask, send_file
app = Flask(__name__)
@app.route("/card/<int:card_id>")
def display_image(card_id):
# The URL of the image you want to display
image_url = (
f"https://gatherer.wizards.com/Handlers/Image.ashx?multiverseid={card_id}&type=card"
)
# Fetch the image from the URL
response = requests.get(image_url)
# Check if the request was successful
if response.status_code == 200:
# Create an in-memory binary stream of the image
image_stream = BytesIO(response.content)
# Send the image as a response
return send_file(image_stream, mimetype="image/png")
else:
# Handle the error case
return "Failed to retrieve image", response.status_code
def main() -> None:
app.run(debug=True)
if __name__ == "__main__":
main()This app should allow you to input different numbers into the URL which then will render a Magic the Gathering card image, or will give an error.