I'm using a web server on PythonAnywhere to run a Flask application. All I'm looking to do is randomly output a gif from a list of URLs. I'm looking to utilize the requests library, and I suspect I need the render_template in order to actually pass the image over. I have been dealing with either view function TypeErrors or outputs of plain text to a URL. I've also incorporated PIL and shutil once or twice but to no functional success.
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')
CodePudding user response:
Use the send_file
method.
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')
CodePudding user response:
You can use {{ variable }} anywhere in your template, not just in the HTML part.
def output():
gif = random.choice(WELCOME_LIST)
return render_template('home.html', gif=gif)
in the home.html
file add a script tag in which you are capturing this passed data
<script>
let gif= {{gif|safe}};
</script>
At this point you have the GIF URL inside your java-script code from where you can edit the HTML part of your code to add this GIF inside the <img>
tags