You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 22:54:03