管理文件

This document describes Django's file access APIs for files such as thoseuploaded by a user. The lower level APIs are general enough that you could usethem for other purposes. If you want to handle "static files" (JS, CSS, etc.),see 管理静态文件(比如图片、JavaScript、CSS).

By default, Django stores files locally, using the MEDIA_ROOT andMEDIA_URL settings. The examples below assume that you're using thesedefaults.

However, Django provides ways to write custom file storage systems thatallow you to completely customize where and how Django stores files. Thesecond half of this document describes how these storage systems work.

Using files in models

When you use a FileField orImageField, Django provides a set of APIs you can useto deal with that file.

Consider the following model, using an ImageField tostore a photo:

  1. from django.db import models
  2.  
  3. class Car(models.Model):
  4. name = models.CharField(max_length=255)
  5. price = models.DecimalField(max_digits=5, decimal_places=2)
  6. photo = models.ImageField(upload_to='cars')

Any Car instance will have a photo attribute that you can use to get atthe details of the attached photo:

  1. >>> car = Car.objects.get(name="57 Chevy")
  2. >>> car.photo
  3. <ImageFieldFile: chevy.jpg>
  4. >>> car.photo.name
  5. 'cars/chevy.jpg'
  6. >>> car.photo.path
  7. '/media/cars/chevy.jpg'
  8. >>> car.photo.url
  9. 'http://media.example.com/cars/chevy.jpg'

This object — car.photo in the example — is a File object, which meansit has all the methods and attributes described below.

注解

The file is saved as part of saving the model in the database, so the actualfile name used on disk cannot be relied on until after the model has beensaved.

For example, you can change the file name by setting the file'sname to a path relative to the file storage'slocation (MEDIA_ROOT if you are using the defaultFileSystemStorage):

  1. >>> import os
  2. >>> from django.conf import settings
  3. >>> initial_path = car.photo.path
  4. >>> car.photo.name = 'cars/chevy_ii.jpg'
  5. >>> new_path = settings.MEDIA_ROOT + car.photo.name
  6. >>> # Move the file on the filesystem
  7. >>> os.rename(initial_path, new_path)
  8. >>> car.save()
  9. >>> car.photo.path
  10. '/media/cars/chevy_ii.jpg'
  11. >>> car.photo.path == new_path
  12. True

The File object

Internally, Django uses a django.core.files.File instance any time itneeds to represent a file.

Most of the time you'll simply use a File that Django's given you (i.e. afile attached to a model as above, or perhaps an uploaded file).

If you need to construct a File yourself, the easiest way is to create oneusing a Python built-in file object:

  1. >>> from django.core.files import File
  2.  
  3. # Create a Python file object using open()
  4. >>> f = open('/path/to/hello.world', 'w')
  5. >>> myfile = File(f)

Now you can use any of the documented attributes and methodsof the File class.

Be aware that files created in this way are not automatically closed.The following approach may be used to close files automatically:

  1. >>> from django.core.files import File
  2.  
  3. # Create a Python file object using open() and the with statement
  4. >>> with open('/path/to/hello.world', 'w') as f:
  5. ... myfile = File(f)
  6. ... myfile.write('Hello World')
  7. ...
  8. >>> myfile.closed
  9. True
  10. >>> f.closed
  11. True

Closing files is especially important when accessing file fields in a loopover a large number of objects. If files are not manually closed afteraccessing them, the risk of running out of file descriptors may arise. Thismay lead to the following error:

  1. IOError: [Errno 24] Too many open files

File storage

Behind the scenes, Django delegates decisions about how and where to store filesto a file storage system. This is the object that actually understands thingslike file systems, opening and reading files, etc.

Django's default file storage is given by the DEFAULT_FILE_STORAGEsetting; if you don't explicitly provide a storage system, this is the one thatwill be used.

See below for details of the built-in default file storage system, and see编写一个自定义存储系统 for information on writing your own filestorage system.

Storage objects

Though most of the time you'll want to use a File object (which delegates tothe proper storage for that file), you can use file storage systems directly.You can create an instance of some custom file storage class, or — often moreuseful — you can use the global default storage system:

  1. >>> from django.core.files.base import ContentFile
  2. >>> from django.core.files.storage import default_storage
  3.  
  4. >>> path = default_storage.save('path/to/file', ContentFile(b'new content'))
  5. >>> path
  6. 'path/to/file'
  7.  
  8. >>> default_storage.size(path)
  9. 11
  10. >>> default_storage.open(path).read()
  11. b'new content'
  12.  
  13. >>> default_storage.delete(path)
  14. >>> default_storage.exists(path)
  15. False

See File storage API for the file storage API.

The built-in filesystem storage class

Django ships with a django.core.files.storage.FileSystemStorage classwhich implements basic local filesystem file storage.

For example, the following code will store uploaded files under/media/photos regardless of what your MEDIA_ROOT setting is:

  1. from django.core.files.storage import FileSystemStorage
  2. from django.db import models
  3.  
  4. fs = FileSystemStorage(location='/media/photos')
  5.  
  6. class Car(models.Model):
  7. ...
  8. photo = models.ImageField(storage=fs)

Custom storage systems work the same way:you can pass them in as the storage argument to aFileField.