如何使用Python requests库结合Flask从URL列表返回随机GIF图片
问题修复方案
存在的问题
- 列表
WELCOME_LIST第一个GIF URL末尾缺失逗号,导致两个URL拼接为非法字符串 - 根路由直接返回
requests.get()的原始响应对象,不符合Flask的响应格式要求,会抛出TypeError /join路由未执行obtainGif函数,直接将函数对象传递给模板,导致页面输出纯文本函数地址- 不需要通过requests代理拉取GIF资源,直接传递远程URL到前端渲染即可,减少服务器性能消耗
修复后的Flask主代码
from flask import Flask, render_template, redirect import random app = Flask(__name__) WELCOME_LIST = [ 'https://cdn.discordapp.com/attachments/891856529928622080/891865614870806568/rgb.gif', 'https://cdn.discordapp.com/attachments/891856529928622080/891865655542964224/racing.gif', 'https://cdn.discordapp.com/attachments/891856529928622080/891897881550802954/comet.gif', 'https://cdn.discordapp.com/attachments/891856529928622080/891897942678581278/harujion.gif', 'https://cdn.discordapp.com/attachments/891856529928622080/891898027126698045/letter.gif', 'https://cdn.discordapp.com/attachments/891856529928622080/891898085909864479/encore.gif', 'https://cdn.discordapp.com/attachments/891856529928622080/891898143627677786/gunjou.gif', 'https://cdn.discordapp.com/attachments/891856529928622080/891898187240050718/haruka.gif', 'https://cdn.discordapp.com/attachments/891856529928622080/891898241900236830/monster.gif', 'https://cdn.discordapp.com/attachments/891856529928622080/891898276339646474/probably.gif', 'https://cdn.discordapp.com/attachments/891856529928622080/891898352617259028/taisho.gif', 'https://cdn.discordapp.com/attachments/891856529928622080/891898425342316624/tracing.gif', ] @app.route('/') def obtainGif(): # 访问根路由直接跳转至随机GIF地址 gif_url = random.choice(WELCOME_LIST) return redirect(gif_url) @app.route('/join') def output(): # 生成随机GIF URL传递给模板渲染 finalize_gif = random.choice(WELCOME_LIST) return render_template('home.html', finalize=finalize_gif) if __name__ == '__main__': app.run(host='0.0.0.0')
模板文件(templates/home.html)代码
<!DOCTYPE html> <html> <head> <title>随机GIF展示</title> </head> <body> <img src="{{ finalize }}" alt="随机欢迎GIF"> </body> </html>
修改说明
- 补全了列表第一个URL后的逗号,修复了非法URL问题
- 移除了不必要的requests、PIL、shutil依赖,不需要服务器中转拉取图片
- 根路由访问时直接跳转到随机GIF地址,符合直接返回图片的需求
/join路由直接传递随机GIF URL到模板,模板通过img标签渲染图片,不会出现纯文本问题
内容的提问来源于stack exchange,提问作者Jatoba
相关产品推荐
相关产品推荐

