File handling. Django Software
Pubblicità
Pubblicità
Django Documentation, Release 1.11.8.dev20171115160334
6.10.7 Python Exceptions
Django raises built-in Python exceptions when appropriate as well. See the Python documentation for further information on the Built-in Exceptions .
6.11 File handling
6.11.1 The File object
The
module and its submodules contain built-in classes for basic file handling in Django.
The File class class File(file_object)
The
class is a thin wrapper around a Python file object with some Django-specific additions. Internally,
Django uses this class when it needs to represent a file.
objects have the following attributes and methods: name
The name of the file including the relative path from
size
The size of the file in bytes.
file
The underlying file object that this class wraps.
Be careful with this attribute in subclasses.
Some subclasses of
and
FieldFile , may replace this attribute with
an object other than a Python file object . In these cases, this attribute may itself be a
subclass (and not necessarily the same subclass). Whenever possible, use the attributes and methods of the subclass itself rather than the those of the subclass’s file attribute.
mode
The read/write mode for the file.
open ( mode=None)
Open or reopen the file (which also does File.seek(0)). The mode argument allows the same values as Python’s built-in open() .
When reopening a file, mode will override whatever mode the file was originally opened with; None means to reopen with the original mode.
__iter__ ()
Iterate over the file yielding one line at a time.
chunks ( chunk_size=None)
Iterate over the file yielding “chunks” of a given size. chunk_size defaults to 64 KB.
This is especially useful with very large files since it allows them to be streamed off disk and avoids storing the whole file in memory.
1024 Chapter 6. API Reference
Django Documentation, Release 1.11.8.dev20171115160334
multiple_chunks ( chunk_size=None)
Returns True if the file is large enough to require multiple chunks to access all of its content give some chunk_size .
close ()
Close the file.
In addition to the listed methods,
exposes the following attributes and methods of its file object: encoding , fileno, flush, isatty, newlines, read, readinto, readline, readlines, seek, softspace , tell, truncate, write, writelines, xreadlines, readable(), writable(), and seekable().
The readable() and writable() methods were added and the seekable() method was made available on Python 2.
The ContentFile class class ContentFile(File)
The ContentFile class inherits from
it operates on string content (bytes also supported), rather than an actual file. For example: from __future__ import unicode_literals from django.core.files.base
import ContentFile f1 = ContentFile( "esta sentencia está en español" ) f2 = ContentFile( b"these are bytes" )
The ImageFile class class ImageFile(file_object)
Django provides a built-in class specifically for images.
django.core.files.images.ImageFile
inherits all the attributes and methods of
File , and additionally provides the following:
width
Width of the image in pixels.
height
Height of the image in pixels.
Additional methods on files attached to objects
Any
that is associated with an object (as with Car.photo, below) will also have a couple of extra methods:
File.save( name , content, save=True)
Saves a new file with the file name and contents provided. This will not replace the existing file, but will create a new file and update the object to point to it. If save is True, the model’s save() method will be called once the file is saved. That is, these two lines:
>>> car.photo.save( 'myphoto.jpg' , content, save=False)
>>> car.save() are equivalent to:
>>> car.photo.save( 'myphoto.jpg' , content, save=True)
6.11. File handling 1025
Django Documentation, Release 1.11.8.dev20171115160334
Note that the content argument must be an instance of either
or of a subclass of
File.delete( save=True)
Removes the file from the model instance and deletes the underlying file. If save is True, the model’s save() method will be called once the file is deleted.
6.11.2 File storage API
Getting the current storage class
Django provides two convenient ways to access the current storage class: class DefaultStorage
provides lazy access to the current default storage system as defined by
uses
internally.
get_storage_class ( import_path=None)
Returns a class or module which implements the storage API.
When called without the import_path parameter get_storage_class will return the current default storage system as defined by
DEFAULT_FILE_STORAGE . If import_path is provided,
get_storage_class will attempt to import the class or module from the given path and will return it if successful. An exception will be raised if the import is unsuccessful.
The FileSystemStorage class class FileSystemStorage(location=None, base_url=None , file_permissions_mode=None , directory_permissions_mode=None)
The
class implements basic file storage on a local filesystem.
It inherits from
and provides implementations for all the public methods thereof.
location
Absolute path to the directory that will hold the files. Defaults to the value of your
setting.
base_url
URL that serves the files stored at this location. Defaults to the value of your
setting.
file_permissions_mode
The file system permissions that the file will receive when it is saved.
Defaults to directory_permissions_mode
The file system permissions that the directory will receive when it is saved.
Defaults to
FILE_UPLOAD_DIRECTORY_PERMISSIONS .
Note: The FileSystemStorage.delete() method will not raise an exception if the given file name does not exist.
get_created_time ( name)
Returns a datetime of the system’s ctime, i.e.
os.path.getctime() . On some systems (like Unix), this is the time of the last metadata change, and on others (like Windows), it’s the creation time of the file.
1026 Chapter 6. API Reference
Django Documentation, Release 1.11.8.dev20171115160334
The Storage class class Storage
The
class provides a standardized API for storing files, along with a set of default behaviors that all other storage systems can inherit or override as necessary.
Note: When methods return naive datetime objects, the effective timezone used will be the current value of os.environ['TZ'] ; note that this is usually set from Django’s
accessed_time ( name)
Returns a naive datetime object containing the last accessed time of the file. For storage systems that aren’t able to return the last accessed time this will raise NotImplementedError instead.
Deprecated since version 1.10: Use
instead.
created_time ( name)
Returns a naive datetime object containing the creation time of the file. For storage systems that aren’t able to return the creation time this will raise NotImplementedError instead.
Deprecated since version 1.10: Use
instead.
delete ( name)
Deletes the file referenced by name. If deletion is not supported on the target storage system this will raise
NotImplementedError instead exists ( name)
Returns True if a file referenced by the given name already exists in the storage system, or False if the name is available for a new file.
get_accessed_time ( name)
Returns a datetime of the last accessed time of the file. For storage systems unable to return the last accessed time this will raise NotImplementedError .
If
is True, returns an aware datetime, otherwise returns a naive datetime in the local timezone.
get_available_name ( name , max_length=None)
Returns a filename based on the name parameter that’s free and available for new content to be written to on the target storage system.
The length of the filename will not exceed max_length, if provided. If a free unique filename cannot be found, a
exception will be raised.
If a file with name already exists, an underscore plus a random 7 character alphanumeric string is appended to the filename before the extension.
get_created_time ( name)
Returns a datetime of the creation time of the file. For storage systems unable to return the creation time this will raise NotImplementedError .
If
is True, returns an aware datetime, otherwise returns a naive datetime in the local timezone.
get_modified_time ( name)
Returns a datetime of the last modified time of the file. For storage systems unable to return the last modified time this will raise NotImplementedError .
If
is True, returns an aware datetime, otherwise returns a naive datetime in the local timezone.
6.11. File handling 1027
Django Documentation, Release 1.11.8.dev20171115160334
get_valid_name ( name)
Returns a filename based on the name parameter that’s suitable for use on the target storage system.
generate_filename ( filename)
Validates the filename by calling
and returns a filename to be passed to the
method.
The filename argument may include a path as returned by
the path won’t be passed to
but will be prepended back to the resulting name.
The default implementation uses os.path
operations. Override this method if that’s not appropriate for your storage.
listdir ( path)
Lists the contents of the specified path, returning a 2-tuple of lists; the first item being directories, the second item being files. For storage systems that aren’t able to provide such a listing, this will raise a
NotImplementedError instead.
modified_time ( name)
Returns a naive datetime object containing the last modified time. For storage systems that aren’t able to return the last modified time, this will raise NotImplementedError instead.
Deprecated since version 1.10: Use
instead.
open ( name , mode=’rb’)
Opens the file given by name. Note that although the returned file is guaranteed to be a File object, it might actually be some subclass. In the case of remote file storage this means that reading/writing could be quite slow, so be warned.
path ( name)
The local filesystem path where the file can be opened using Python’s standard open(). For storage systems that aren’t accessible from the local filesystem, this will raise NotImplementedError instead.
save ( name , content, max_length=None)
Saves a new file using the storage system, preferably with the name specified. If there already exists a file with this name name, the storage system may modify the filename as necessary to get a unique name. The actual name of the stored file will be returned.
The max_length argument is passed along to
The content argument must be an instance of
or a file-like object that can be wrapped in File.
size ( name)
Returns the total size, in bytes, of the file referenced by name. For storage systems that aren’t able to return the file size this will raise NotImplementedError instead.
url ( name)
Returns the URL where the contents of the file referenced by name can be accessed. For storage systems that don’t support access by URL this will raise NotImplementedError instead.
6.11.3 Uploaded Files and Upload Handlers
Uploaded files class UploadedFile
During file uploads, the actual file data is stored in
. Each entry in this dictionary is an
UploadedFile object (or a subclass) – a simple wrapper around an uploaded file. You’ll usually use one of these methods to access the uploaded content:
1028 Chapter 6. API Reference
Django Documentation, Release 1.11.8.dev20171115160334
UploadedFile.read()
Read the entire uploaded data from the file. Be careful with this method: if the uploaded file is huge it can overwhelm your system if you try to read it into memory. You’ll probably want to use chunks() instead; see below.
UploadedFile.multiple_chunks( chunk_size=None)
Returns True if the uploaded file is big enough to require reading in multiple chunks. By default this will be any file larger than 2.5 megabytes, but that’s configurable; see below.
UploadedFile.chunks( chunk_size=None)
A generator returning chunks of the file. If multiple_chunks() is True, you should use this method in a loop instead of read().
In practice, it’s often easiest simply to use chunks() all the time. Looping over chunks() instead of using read() ensures that large files don’t overwhelm your system’s memory.
Here are some useful attributes of UploadedFile:
UploadedFile.name
The name of the uploaded file (e.g. my_file.txt).
UploadedFile.size
The size, in bytes, of the uploaded file.
UploadedFile.content_type
The content-type header uploaded with the file (e.g. text/plain or application/pdf). Like any data supplied by the user, you shouldn’t trust that the uploaded file is actually this type. You’ll still need to validate that the file contains the content that the content-type header claims – “trust but verify.”
UploadedFile.content_type_extra
A dictionary containing extra parameters passed to the content-type header. This is typically provided by services, such as Google App Engine, that intercept and handle file uploads on your behalf. As a result your handler may not receive the uploaded file content, but instead a URL or other pointer to the file. (see RFC 2388 section 5.3).
UploadedFile.charset
For text/* content-types, the character set (i.e. utf8) supplied by the browser. Again, “trust but verify” is the best policy here.
Note: Like regular Python files, you can read the file line-by-line simply by iterating over the uploaded file: for line in uploadedfile: do_something_with(line)
Lines are split using universal newlines . The following are recognized as ending a line: the Unix end-of-line convention '\n', the Windows convention '\r\n', and the old Macintosh convention '\r'.
Subclasses of UploadedFile include: class TemporaryUploadedFile
A file uploaded to a temporary location (i.e.
stream-to-disk).
This class is used by the
TemporaryFileUploadHandler . In addition to the methods from
UploadedFile , it has one addi-
tional method:
TemporaryUploadedFile.temporary_file_path()
Returns the full path to the temporary uploaded file.
6.11. File handling 1029
Django Documentation, Release 1.11.8.dev20171115160334
class InMemoryUploadedFile
A file uploaded into memory (i.e.
stream-to-memory).
This class is used by the
Built-in upload handlers
Together the
and
provide Django’s default file upload behavior of reading small files into memory and large ones onto disk. They are located in django.core.
files.uploadhandler
.
class MemoryFileUploadHandler
File upload handler to stream uploads into memory (used for small files).
class TemporaryFileUploadHandler
Upload handler that streams data into a temporary file using
Writing custom upload handlers class FileUploadHandler
All file upload handlers should be subclasses of django.core.files.uploadhandler.
FileUploadHandler . You can define upload handlers wherever you wish.
Required methods
Custom file upload handlers must define the following methods:
FileUploadHandler.receive_data_chunk( raw_data , start)
Receives a “chunk” of data from the file upload.
raw_data is a byte string containing the uploaded data.
start is the position in the file where this raw_data chunk begins.
The data you return will get fed into the subsequent upload handlers’ receive_data_chunk methods. In this way, one handler can be a “filter” for other handlers.
Return None from receive_data_chunk to short-circuit remaining upload handlers from getting this chunk. This is useful if you’re storing the uploaded data yourself and don’t want future handlers to store a copy of the data.
If you raise a StopUpload or a SkipFile exception, the upload will abort or the file will be completely skipped.
FileUploadHandler.file_complete( file_size)
Called when a file has finished uploading.
The handler should return an UploadedFile object that will be stored in request.FILES. Handlers may also return None to indicate that the UploadedFile object should come from subsequent upload handlers.
Optional methods
Custom upload handlers may also define any of the following optional methods or attributes:
1030 Chapter 6. API Reference
Scarica
Pubblicità