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.
from flask import Flask, send_file
import requests
from io import BytesIO
= Flask(__name__)
app
@app.route('/card/<int:card_id>')
def display_image(card_id):
# The URL of the image you want to display
= f'https://gatherer.wizards.com/Handlers/Image.ashx?multiverseid={card_id}&type=card'
image_url
# Fetch the image from the URL
= requests.get(image_url)
response
# Check if the request was successful
if response.status_code == 200:
# Create an in-memory binary stream of the image
= BytesIO(response.content)
image_stream
# 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
if __name__ == '__main__':
=True) app.run(debug
This app should allow you to input different numbers into the URL which then will render an Magic the Gathering card image, or will give an error.