URL generation rule explained for file uploads
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sourya Vatsyayan · committed by Sourya Vatsyayan · parent d2a3804 · Browse files · 1 file·+0 added−190 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
1 file+0 added−190 removed
- other:+0 added−190 removed
Provenance
- Commit
50fef79- Tree
14f8e1c- Author
Sourya Vatsyayan <souryavatsyayan@gmail.com>- Committer
Sourya Vatsyayan <souryavatsyayan@gmail.com>- Parent
d2a3804
1 file changed+0 added−190 removed
deleted:docs/patterns/fileuploads.rst~-190 removed
1-.. _uploading-files:2-3-Uploading Files4-===============5-6-Ah yes, the good old problem of file uploads. The basic idea of file7-uploads is actually quite simple. It basically works like this:8-9-1. A ``<form>`` tag is marked with ``enctype=multipart/form-data``10- and an ``<input type=file>`` is placed in that form.11-2. The application accesses the file from the :attr:`~flask.request.files`12- dictionary on the request object.13-3. use the :meth:`~werkzeug.datastructures.FileStorage.save` method of the file to save14- the file permanently somewhere on the filesystem.15-16-A Gentle Introduction17----------------------18-19-Let's start with a very basic application that uploads a file to a20-specific upload folder and displays a file to the user. Let's look at the21-bootstrapping code for our application::22-23- import os24- from flask import Flask, request, redirect, url_for25- from werkzeug.utils import secure_filename26-27- UPLOAD_FOLDER = '/path/to/the/uploads'28- ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])29-30- app = Flask(__name__)31- app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER32-33-So first we need a couple of imports. Most should be straightforward, the34-:func:`werkzeug.secure_filename` is explained a little bit later. The35-``UPLOAD_FOLDER`` is where we will store the uploaded files and the36-``ALLOWED_EXTENSIONS`` is the set of allowed file extensions. Then we add a37-URL rule by hand to the application. Now usually we're not doing that, so38-why here? The reasons is that we want the webserver (or our development39-server) to serve these files for us and so we only need a rule to generate40-the URL to these files.41-42-Why do we limit the extensions that are allowed? You probably don't want43-your users to be able to upload everything there if the server is directly44-sending out the data to the client. That way you can make sure that users45-are not able to upload HTML files that would cause XSS problems (see46-:ref:`xss`). Also make sure to disallow ``.php`` files if the server47-executes them, but who has PHP installed on his server, right? :)48-49-Next the functions that check if an extension is valid and that uploads50-the file and redirects the user to the URL for the uploaded file::51-52- def allowed_file(filename):53- return '.' in filename and \54- filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS55-56- @app.route('/', methods=['GET', 'POST'])57- def upload_file():58- if request.method == 'POST':59- # check if the post request has the file part60- if 'file' not in request.files:61- flash('No file part')62- return redirect(request.url)63- file = request.files['file']64- # if user does not select file, browser also65- # submit a empty part without filename66- if file.filename == '':67- flash('No selected file')68- return redirect(request.url)69- if file and allowed_file(file.filename):70- filename = secure_filename(file.filename)71- file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))72- return redirect(url_for('uploaded_file',73- filename=filename))74- return '''75- <!doctype html>76- <title>Upload new File</title>77- <h1>Upload new File</h1>78- <form action="" method=post enctype=multipart/form-data>79- <p><input type=file name=file>80- <input type=submit value=Upload>81- </form>82- '''83-84-So what does that :func:`~werkzeug.utils.secure_filename` function actually do?85-Now the problem is that there is that principle called "never trust user86-input". This is also true for the filename of an uploaded file. All87-submitted form data can be forged, and filenames can be dangerous. For88-the moment just remember: always use that function to secure a filename89-before storing it directly on the filesystem.90-91-.. admonition:: Information for the Pros92-93- So you're interested in what that :func:`~werkzeug.utils.secure_filename`94- function does and what the problem is if you're not using it? So just95- imagine someone would send the following information as `filename` to96- your application::97-98- filename = "../../../../home/username/.bashrc"99-100- Assuming the number of ``../`` is correct and you would join this with101- the ``UPLOAD_FOLDER`` the user might have the ability to modify a file on102- the server's filesystem he or she should not modify. This does require some103- knowledge about how the application looks like, but trust me, hackers104- are patient :)105-106- Now let's look how that function works:107-108- >>> secure_filename('../../../../home/username/.bashrc')109- 'home_username_.bashrc'110-111-Now one last thing is missing: the serving of the uploaded files. As of112-Flask 0.5 we can use a function that does that for us::113-114- from flask import send_from_directory115-116- @app.route('/uploads/<filename>')117- def uploaded_file(filename):118- return send_from_directory(app.config['UPLOAD_FOLDER'],119- filename)120-121-Alternatively you can register `uploaded_file` as `build_only` rule and122-use the :class:`~werkzeug.wsgi.SharedDataMiddleware`. This also works with123-older versions of Flask::124-125- from werkzeug import SharedDataMiddleware126- app.add_url_rule('/uploads/<filename>', 'uploaded_file',127- build_only=True)128- app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {129- '/uploads': app.config['UPLOAD_FOLDER']130- })131-132-If you now run the application everything should work as expected.133-134-135-Improving Uploads136------------------137-138-.. versionadded:: 0.6139-140-So how exactly does Flask handle uploads? Well it will store them in the141-webserver's memory if the files are reasonable small otherwise in a142-temporary location (as returned by :func:`tempfile.gettempdir`). But how143-do you specify the maximum file size after which an upload is aborted? By144-default Flask will happily accept file uploads to an unlimited amount of145-memory, but you can limit that by setting the ``MAX_CONTENT_LENGTH``146-config key::147-148- from flask import Flask, Request149-150- app = Flask(__name__)151- app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024152-153-The code above will limited the maximum allowed payload to 16 megabytes.154-If a larger file is transmitted, Flask will raise an155-:exc:`~werkzeug.exceptions.RequestEntityTooLarge` exception.156-157-This feature was added in Flask 0.6 but can be achieved in older versions158-as well by subclassing the request object. For more information on that159-consult the Werkzeug documentation on file handling.160-161-162-Upload Progress Bars163---------------------164-165-A while ago many developers had the idea to read the incoming file in166-small chunks and store the upload progress in the database to be able to167-poll the progress with JavaScript from the client. Long story short: the168-client asks the server every 5 seconds how much it has transmitted169-already. Do you realize the irony? The client is asking for something it170-should already know.171-172-Now there are better solutions to that work faster and more reliable. The173-web changed a lot lately and you can use HTML5, Java, Silverlight or Flash174-to get a nicer uploading experience on the client side. Look at the175-following libraries for some nice examples how to do that:176-177-- `Plupload <http://www.plupload.com/>`_ - HTML5, Java, Flash178-- `SWFUpload <http://www.swfupload.org/>`_ - Flash179-- `JumpLoader <http://jumploader.com/>`_ - Java180-181-182-An Easier Solution183-------------------184-185-Because the common pattern for file uploads exists almost unchanged in all186-applications dealing with uploads, there is a Flask extension called187-`Flask-Uploads`_ that implements a full fledged upload mechanism with188-white and blacklisting of extensions and more.189-190-.. _Flask-Uploads: http://pythonhosted.org/Flask-Uploads/