如何从带有Python请求的列表返回随机gif



我在PythonAnywhere上使用web服务器来运行Flask应用程序。我所要做的就是从url列表中随机输出一个gif。我正在寻找利用请求库,我怀疑我需要render_template,以便实际传递图像。我一直在处理视图函数TypeErrors或纯文本输出到URL。我也合并过PIL和shutil一两次,但都没有成功。

from flask import Flask, render_template
import random
import requests
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 = random.choice(WELCOME_LIST)
response = requests.get(gif)
return response.raw
@app.route('/join')
def output():
finalize = obtainGif
return render_template('home.html', finalize=finalize)
if __name__ == '__main__':
app.run(host='0.0.0.0')

使用send_file方法

from flask import Flask, render_template, send_file
def obtainGif():
gif = random.choice(WELCOME_LIST)
response = requests.get(gif, stream=True)
return send_file(response.raw, mimetype='image/gif')

你可以在模板的任何地方使用{{variable}},而不仅仅是在HTML部分。


def output():
gif = random.choice(WELCOME_LIST)
return render_template('home.html', gif=gif)

home.html文件中添加一个脚本标记,在其中捕获传递的数据

<script>
let gif= {{gif|safe}};
</script>
在这一点上,你有GIF URL在你的java脚本代码中,从你可以编辑你的代码的HTML部分,以添加这个GIF在<img>标签