Files
iamzhaohaibo b408a1e1b2 add Web/ProxyImagesDemo/demo.py.
当图片无法获取显示(状态码403时)可以参考使用如下图片代理

Signed-off-by: iamzhaohaibo <941604465@qq.com>
2026-01-03 08:49:49 +00:00

31 lines
1.2 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

@app.route('/proxy-image/<path:image_url>')
def proxy_image(image_url):
"""
图片代理路由,用于绕过跨域限制
"""
try:
# 重新构建完整URL如果需要的话
if not image_url.startswith(('http://', 'https://')):
full_url = 'https://' + image_url.lstrip('/')
else:
full_url = image_url
# 添加请求头来模拟浏览器请求
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Referer': 'https://movie.douban.com/',
'Accept': 'image/webp,image/apng,image/*,*/*;q=0.8'
}
response = requests.get(full_url, headers=headers, timeout=10)
if response.status_code == 200:
# 返回图片内容
image_data = BytesIO(response.content)
content_type = response.headers.get('Content-Type', 'image/jpeg')
return send_file(image_data, mimetype=content_type)
else:
abort(404)
except Exception as e:
print(f"Error fetching image: {e}")
abort(404)