How to create a simple image proxy server using Flask in Python

Published on Aug. 22, 2023, 12:16 p.m.

To create a simple image proxy server using Flask in Python, you can use the requests library to download the image from the remote URL and return it as a response from the Flask route. Here’s an example code that demonstrates how to create a Flask route that downloads a remote image and returns it as the response:

from flask import Flask, Response
import requests

app = Flask(__name__)

@app.route('/image/<path:url>')
def image_proxy(url):
    response = requests.get(url)
    headers = {'Content-Type': 'image/jpeg'}
    return Response(response.content, headers=headers)

if __name__ == '__main__':
    app.run()

In this code, we define a Flask route that takes a url parameter in the route path. We then use the requests library to download the image from the remote URL, and return a Response object with the response content and headers. Note that we set the Content-Type header to image/jpeg to indicate that the response content is an image in JPEG format.

To run the Flask app and test the image proxy route, you can simply run the code in your terminal and navigate to http://localhost:5000/image/<image_url>, where <image_url> is the URL of the remote image you want to proxy.

Tags: