深度阅读

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

作者
作者
2023年08月22日
更新时间
12.23 分钟
阅读时间
0
阅读量

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.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。