~ubuntu-branches/debian/sid/python-django/sid

« back to all changes in this revision

Viewing changes to docs/topics/http/file-uploads.txt

  • Committer: Package Import Robot
  • Author(s): Raphaël Hertzog
  • Date: 2014-09-17 14:15:11 UTC
  • mfrom: (1.3.17) (6.2.18 experimental)
  • Revision ID: package-import@ubuntu.com-20140917141511-icneokthe9ww5sk4
Tags: 1.7-2
* Release to unstable.
* Add a migrate-south sample script to help users apply their South
  migrations. Thanks to Brian May.

Show diffs side-by-side

added added

removed removed

Lines of Context:
26
26
 
27
27
    class UploadFileForm(forms.Form):
28
28
        title = forms.CharField(max_length=50)
29
 
        file  = forms.FileField()
 
29
        file = forms.FileField()
30
30
 
31
31
A view handling this form will receive the file data in
32
32
:attr:`request.FILES <django.http.HttpRequest.FILES>`, which is a dictionary
64
64
Notice that we have to pass :attr:`request.FILES <django.http.HttpRequest.FILES>`
65
65
into the form's constructor; this is how file data gets bound into a form.
66
66
 
67
 
Handling uploaded files
68
 
-----------------------
69
 
 
70
 
.. class:: UploadedFile
71
 
 
72
 
    The final piece of the puzzle is handling the actual file data from
73
 
    :attr:`request.FILES <django.http.HttpRequest.FILES>`. Each entry in this
74
 
    dictionary is an ``UploadedFile`` object -- a simple wrapper around an uploaded
75
 
    file. You'll usually use one of these methods to access the uploaded content:
76
 
 
77
 
    .. method:: read()
78
 
 
79
 
        Read the entire uploaded data from the file. Be careful with this
80
 
        method: if the uploaded file is huge it can overwhelm your system if you
81
 
        try to read it into memory. You'll probably want to use ``chunks()``
82
 
        instead; see below.
83
 
 
84
 
    .. method:: multiple_chunks()
85
 
 
86
 
        Returns ``True`` if the uploaded file is big enough to require
87
 
        reading in multiple chunks. By default this will be any file
88
 
        larger than 2.5 megabytes, but that's configurable; see below.
89
 
 
90
 
    .. method:: chunks()
91
 
 
92
 
        A generator returning chunks of the file. If ``multiple_chunks()`` is
93
 
        ``True``, you should use this method in a loop instead of ``read()``.
94
 
 
95
 
        In practice, it's often easiest simply to use ``chunks()`` all the time;
96
 
        see the example below.
97
 
 
98
 
    .. attribute:: name
99
 
 
100
 
        The name of the uploaded file (e.g. ``my_file.txt``).
101
 
 
102
 
    .. attribute:: size
103
 
 
104
 
        The size, in bytes, of the uploaded file.
105
 
 
106
 
There are a few other methods and attributes available on ``UploadedFile``
107
 
objects; see `UploadedFile objects`_ for a complete reference.
108
 
 
109
 
Putting it all together, here's a common way you might handle an uploaded file::
 
67
Here's a common way you might handle an uploaded file::
110
68
 
111
69
    def handle_uploaded_file(f):
112
70
        with open('some/file/name.txt', 'wb+') as destination:
116
74
Looping over ``UploadedFile.chunks()`` instead of using ``read()`` ensures that
117
75
large files don't overwhelm your system's memory.
118
76
 
119
 
Where uploaded data is stored
120
 
-----------------------------
121
 
 
122
 
Before you save uploaded files, the data needs to be stored somewhere.
123
 
 
124
 
By default, if an uploaded file is smaller than 2.5 megabytes, Django will hold
125
 
the entire contents of the upload in memory. This means that saving the file
126
 
involves only a read from memory and a write to disk and thus is very fast.
127
 
 
128
 
However, if an uploaded file is too large, Django will write the uploaded file
129
 
to a temporary file stored in your system's temporary directory. On a Unix-like
130
 
platform this means you can expect Django to generate a file called something
131
 
like ``/tmp/tmpzfp6I6.upload``. If an upload is large enough, you can watch this
132
 
file grow in size as Django streams the data onto disk.
133
 
 
134
 
These specifics -- 2.5 megabytes; ``/tmp``; etc. -- are simply "reasonable
135
 
defaults". Read on for details on how you can customize or completely replace
136
 
upload behavior.
137
 
 
138
 
Changing upload handler behavior
139
 
--------------------------------
140
 
 
141
 
Three settings control Django's file upload behavior:
142
 
 
143
 
:setting:`FILE_UPLOAD_MAX_MEMORY_SIZE`
144
 
    The maximum size, in bytes, for files that will be uploaded into memory.
145
 
    Files larger than :setting:`FILE_UPLOAD_MAX_MEMORY_SIZE` will be
146
 
    streamed to disk.
147
 
 
148
 
    Defaults to 2.5 megabytes.
149
 
 
150
 
:setting:`FILE_UPLOAD_TEMP_DIR`
151
 
    The directory where uploaded files larger than
152
 
    :setting:`FILE_UPLOAD_MAX_MEMORY_SIZE` will be stored.
153
 
 
154
 
    Defaults to your system's standard temporary directory (i.e. ``/tmp`` on
155
 
    most Unix-like systems).
156
 
 
157
 
:setting:`FILE_UPLOAD_PERMISSIONS`
158
 
    The numeric mode (i.e. ``0o644``) to set newly uploaded files to. For
159
 
    more information about what these modes mean, see the documentation for
160
 
    :func:`os.chmod`.
161
 
 
162
 
    If this isn't given or is ``None``, you'll get operating-system
163
 
    dependent behavior. On most platforms, temporary files will have a mode
164
 
    of ``0o600``, and files saved from memory will be saved using the
165
 
    system's standard umask.
166
 
 
167
 
    For security reasons, these permissions aren't applied to the temporary
168
 
    files that are stored in :setting:`FILE_UPLOAD_TEMP_DIR`.
169
 
 
170
 
    .. warning::
171
 
 
172
 
        If you're not familiar with file modes, please note that the leading
173
 
        ``0`` is very important: it indicates an octal number, which is the
174
 
        way that modes must be specified. If you try to use ``644``, you'll
175
 
        get totally incorrect behavior.
176
 
 
177
 
        **Always prefix the mode with a 0.**
178
 
 
179
 
:setting:`FILE_UPLOAD_HANDLERS`
180
 
    The actual handlers for uploaded files. Changing this setting allows
181
 
    complete customization -- even replacement -- of Django's upload
182
 
    process. See `upload handlers`_, below, for details.
183
 
 
184
 
    Defaults to::
185
 
 
186
 
        ("django.core.files.uploadhandler.MemoryFileUploadHandler",
187
 
         "django.core.files.uploadhandler.TemporaryFileUploadHandler",)
188
 
 
189
 
    Which means "try to upload to memory first, then fall back to temporary
190
 
    files."
 
77
There are a few other methods and attributes available on ``UploadedFile``
 
78
objects; see :class:`UploadedFile` for a complete reference.
191
79
 
192
80
Handling uploaded files with a model
193
81
------------------------------------
234
122
            form = UploadFileForm()
235
123
        return render(request, 'upload.html', {'form': form})
236
124
 
237
 
 
238
 
``UploadedFile`` objects
239
 
========================
240
 
 
241
 
In addition to those inherited from :class:`~django.core.files.File`, all
242
 
``UploadedFile`` objects define the following methods/attributes:
243
 
 
244
 
.. attribute:: UploadedFile.content_type
245
 
 
246
 
    The content-type header uploaded with the file (e.g. :mimetype:`text/plain`
247
 
    or :mimetype:`application/pdf`). Like any data supplied by the user, you
248
 
    shouldn't trust that the uploaded file is actually this type. You'll still
249
 
    need to validate that the file contains the content that the content-type
250
 
    header claims -- "trust but verify."
251
 
 
252
 
.. attribute:: UploadedFile.charset
253
 
 
254
 
    For :mimetype:`text/*` content-types, the character set (i.e. ``utf8``)
255
 
    supplied by the browser. Again, "trust but verify" is the best policy here.
256
 
 
257
 
.. attribute:: UploadedFile.temporary_file_path()
258
 
 
259
 
    Only files uploaded onto disk will have this method; it returns the full
260
 
    path to the temporary uploaded file.
261
 
 
262
 
.. note::
263
 
 
264
 
    Like regular Python files, you can read the file line-by-line simply by
265
 
    iterating over the uploaded file:
266
 
 
267
 
    .. code-block:: python
268
 
 
269
 
        for line in uploadedfile:
270
 
            do_something_with(line)
271
 
 
272
 
    However, *unlike* standard Python files, :class:`UploadedFile` only
273
 
    understands ``\n`` (also known as "Unix-style") line endings. If you know
274
 
    that you need to handle uploaded files with different line endings, you'll
275
 
    need to do so in your view.
276
 
 
277
125
Upload Handlers
278
126
===============
279
127
 
 
128
.. currentmodule:: django.core.files.uploadhandler
 
129
 
280
130
When a user uploads a file, Django passes off the file data to an *upload
281
131
handler* -- a small class that handles file data as it gets uploaded. Upload
282
132
handlers are initially defined in the :setting:`FILE_UPLOAD_HANDLERS` setting,
285
135
    ("django.core.files.uploadhandler.MemoryFileUploadHandler",
286
136
     "django.core.files.uploadhandler.TemporaryFileUploadHandler",)
287
137
 
288
 
Together the ``MemoryFileUploadHandler`` and ``TemporaryFileUploadHandler``
289
 
provide Django's default file upload behavior of reading small files into memory
290
 
and large ones onto disk.
 
138
Together :class:`MemoryFileUploadHandler` and
 
139
:class:`TemporaryFileUploadHandler` provide Django's default file upload
 
140
behavior of reading small files into memory and large ones onto disk.
291
141
 
292
142
You can write custom handlers that customize how Django handles files. You
293
143
could, for example, use custom handlers to enforce user-level quotas, compress
294
144
data on the fly, render progress bars, and even send data to another storage
295
 
location directly without storing it locally.
 
145
location directly without storing it locally. See :ref:`custom_upload_handlers`
 
146
for details on how you can customize or completely replace upload behavior.
296
147
 
297
148
.. _modifying_upload_handlers_on_the_fly:
298
149
 
 
150
Where uploaded data is stored
 
151
-----------------------------
 
152
 
 
153
Before you save uploaded files, the data needs to be stored somewhere.
 
154
 
 
155
By default, if an uploaded file is smaller than 2.5 megabytes, Django will hold
 
156
the entire contents of the upload in memory. This means that saving the file
 
157
involves only a read from memory and a write to disk and thus is very fast.
 
158
 
 
159
However, if an uploaded file is too large, Django will write the uploaded file
 
160
to a temporary file stored in your system's temporary directory. On a Unix-like
 
161
platform this means you can expect Django to generate a file called something
 
162
like ``/tmp/tmpzfp6I6.upload``. If an upload is large enough, you can watch this
 
163
file grow in size as Django streams the data onto disk.
 
164
 
 
165
These specifics -- 2.5 megabytes; ``/tmp``; etc. -- are simply "reasonable
 
166
defaults" which can be customized as described in the next section.
 
167
 
 
168
Changing upload handler behavior
 
169
--------------------------------
 
170
 
 
171
There are a few settings which control Django's file upload behavior. See
 
172
:ref:`File Upload Settings <file-upload-settings>` for details.
 
173
 
299
174
Modifying upload handlers on the fly
300
175
------------------------------------
301
176
 
354
229
        @csrf_protect
355
230
        def _upload_file_view(request):
356
231
            ... # Process request
357
 
 
358
 
 
359
 
Writing custom upload handlers
360
 
------------------------------
361
 
 
362
 
All file upload handlers should be subclasses of
363
 
``django.core.files.uploadhandler.FileUploadHandler``. You can define upload
364
 
handlers wherever you wish.
365
 
 
366
 
Required methods
367
 
~~~~~~~~~~~~~~~~
368
 
 
369
 
Custom file upload handlers **must** define the following methods:
370
 
 
371
 
``FileUploadHandler.receive_data_chunk(raw_data, start)``
372
 
    Receives a "chunk" of data from the file upload.
373
 
 
374
 
    ``raw_data`` is a byte string containing the uploaded data.
375
 
 
376
 
    ``start`` is the position in the file where this ``raw_data`` chunk
377
 
    begins.
378
 
 
379
 
    The data you return will get fed into the subsequent upload handlers'
380
 
    ``receive_data_chunk`` methods. In this way, one handler can be a
381
 
    "filter" for other handlers.
382
 
 
383
 
    Return ``None`` from ``receive_data_chunk`` to short-circuit remaining
384
 
    upload handlers from getting this chunk. This is useful if you're
385
 
    storing the uploaded data yourself and don't want future handlers to
386
 
    store a copy of the data.
387
 
 
388
 
    If you raise a ``StopUpload`` or a ``SkipFile`` exception, the upload
389
 
    will abort or the file will be completely skipped.
390
 
 
391
 
``FileUploadHandler.file_complete(file_size)``
392
 
    Called when a file has finished uploading.
393
 
 
394
 
    The handler should return an ``UploadedFile`` object that will be stored
395
 
    in ``request.FILES``. Handlers may also return ``None`` to indicate that
396
 
    the ``UploadedFile`` object should come from subsequent upload handlers.
397
 
 
398
 
Optional methods
399
 
~~~~~~~~~~~~~~~~
400
 
 
401
 
Custom upload handlers may also define any of the following optional methods or
402
 
attributes:
403
 
 
404
 
``FileUploadHandler.chunk_size``
405
 
    Size, in bytes, of the "chunks" Django should store into memory and feed
406
 
    into the handler. That is, this attribute controls the size of chunks
407
 
    fed into ``FileUploadHandler.receive_data_chunk``.
408
 
 
409
 
    For maximum performance the chunk sizes should be divisible by ``4`` and
410
 
    should not exceed 2 GB (2\ :sup:`31` bytes) in size. When there are
411
 
    multiple chunk sizes provided by multiple handlers, Django will use the
412
 
    smallest chunk size defined by any handler.
413
 
 
414
 
    The default is 64*2\ :sup:`10` bytes, or 64 KB.
415
 
 
416
 
``FileUploadHandler.new_file(field_name, file_name, content_type, content_length, charset)``
417
 
    Callback signaling that a new file upload is starting. This is called
418
 
    before any data has been fed to any upload handlers.
419
 
 
420
 
    ``field_name`` is a string name of the file ``<input>`` field.
421
 
 
422
 
    ``file_name`` is the unicode filename that was provided by the browser.
423
 
 
424
 
    ``content_type`` is the MIME type provided by the browser -- E.g.
425
 
    ``'image/jpeg'``.
426
 
 
427
 
    ``content_length`` is the length of the image given by the browser.
428
 
    Sometimes this won't be provided and will be ``None``.
429
 
 
430
 
    ``charset`` is the character set (i.e. ``utf8``) given by the browser.
431
 
    Like ``content_length``, this sometimes won't be provided.
432
 
 
433
 
    This method may raise a ``StopFutureHandlers`` exception to prevent
434
 
    future handlers from handling this file.
435
 
 
436
 
``FileUploadHandler.upload_complete()``
437
 
    Callback signaling that the entire upload (all files) has completed.
438
 
 
439
 
``FileUploadHandler.handle_raw_input(input_data, META, content_length, boundary, encoding)``
440
 
    Allows the handler to completely override the parsing of the raw
441
 
    HTTP input.
442
 
 
443
 
    ``input_data`` is a file-like object that supports ``read()``-ing.
444
 
 
445
 
    ``META`` is the same object as ``request.META``.
446
 
 
447
 
    ``content_length`` is the length of the data in ``input_data``. Don't
448
 
    read more than ``content_length`` bytes from ``input_data``.
449
 
 
450
 
    ``boundary`` is the MIME boundary for this request.
451
 
 
452
 
    ``encoding`` is the encoding of the request.
453
 
 
454
 
    Return ``None`` if you want upload handling to continue, or a tuple of
455
 
    ``(POST, FILES)`` if you want to return the new data structures suitable
456
 
    for the request directly.