In this Flask Web development tutorial, we're going to be discussing how to return files rather than templates.
Let's consider that we have a page with a download button for some file:
__init__.py
from flask import send_file # ... other code .... @app.route('/file-downloads/') def file_downloads(): try: return render_template('downloads.html') except Exception as e: return str(e)
templates/downloads.html
{% extends "header.html" %} {% block body %} <body class="body"> <div class="container" align="left"> <a href="/return-files/" target="blank"><button class='btn btn-default'>Download!</button></a> </div> </body> {% endblock %}
We can see that we're sending the person to /return-files/, which doesn't exist yet, let's make that.
__init__.py
@app.route('/return-files/') def return_files_tut(): try: return send_file('/var/www/PythonProgramming/PythonProgramming/static/images/python.jpg', attachment_filename='python.jpg') except Exception as e: return str(e)
In this case, if a person goes to /file-downloads/, and clicks the download button, they will get an image returned. How about a pdf?
@app.route('/return-files/') def return_files_tut(): try: return send_file('/var/www/PythonProgramming/PythonProgramming/static/ohhey.pdf', attachment_filename='ohhey.pdf') except Exception as e: return str(e)
Simple enough, but what if you want to protect the files in some way. On PythonProgramming.net, for example, I let subscribers just download the videos, but you have to be a subscriber. Most downloads need to be in the static directory, which is totally public, so how would one go about protecting a file from the general public? That's what we'll be talking about in the next tutorial.