Manage files

This is the 21st day of my participation in the August Text Challenge.More challenges in August

Thank you for meeting you. I’m Y Dazhuang

By Y Dazhuang Link: juejin.cn/user/756923… The copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source.

🌊🌈

Part of the article and pictures from the Internet, if you have any questions please contact me

🌊🌈

By Y Dazhuang Link: juejin.cn/post/699831… The copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source.

By default, Django uses MEDIA_ROOT and MEDIA_URL to set up local storage. The examples below assume that you are using these defaults.

1. Use files in the model

Django provides a set of apis for handling files when you use FileField or ImageField.

Consider the following model, which uses ImageField to store photos:

from django.db import models
​
class Car(models.Model) :
    price = models.DecimalField(max_digits=5, decimal_places=2)
    photo = models.ImageField(upload_to='cars') # path name
Copy the code

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

>>> car = Car.objects.get(pk=id)
>>> car.photo
<ImageFieldFile: cars/test.jpg>
>>> car.photo.name
'cars/test.jpg'
>>> car.photo.path
'/media/cars/test.jpg'
>>> car.photo.url
'http://media.example.com/cars/test.jpg'
Copy the code

Car. Photo is a File object, which means it has all the methods and attributes described below.

Pay attention to

The file is in the database as part of the saved model, so you cannot rely on the actual file name used on disk until the model is saved.

2. File object

Internally, Django uses Django.core.files.file whenever it needs to represent a File

Most of the time you just need to use the files provided with Django (that is, files attached to the above model or files already uploaded).

If you need to build a File yourself, the easiest way is to create one using Python’s built-in File object:

>>> from django.core.files import File
​
>>> f = open('/path/to/hello.txt'.'w')
>>> myfile = File(f)
Copy the code

Now you can use any property and method of the File class.

Note that files created here will not be closed automatically. The following methods can be used to automatically close files:

>>> from django.core.files import File
​
>>> with open('/path/to/hello.world'.'w') as f:
.    myfile = File(f)
.    myfile.write('Hello World')...>>> myfile.closed
True
>>> f.closed
True
Copy the code

Closing files is especially important when a large number of objects are iterating through file fields. If the file cannot be closed manually after access, there may be a risk of file descriptor overflow.

OSError: [Errno 24] Too many open files
Copy the code

3. File storage

Behind the scenes, Django delegates decisions about how and where to store files to the file storage system. This object actually understands the file system, opens and reads files, and so on.

Django’s default file storage is configured using DEFAULT_FILE_STORAGE. If you do not explicitly provide a storage system, the default configuration is used.

3.1 Storing Objects

Although you can use File objects most of the time (delegating the File to the appropriate store), you can use the File storage system directly. You can create some examples of custom file storage classes, or use the generally more useful global default storage system:

>>> from django.core.files.base import ContentFile
>>> from django.core.files.storage import default_storage
​
>>> path = default_storage.save('path/to/file', ContentFile(b'new content'))
>>> path
'path/to/file'
​
>>> default_storage.size(path)
11
>>> default_storage.open(path).read()
b'new content'
​
>>> default_storage.delete(path)
>>> default_storage.exists(path)
False
Copy the code

3.2 Built-in file storage classes

Django comes with a Django. Core. Files. Storage. FileSystemStorage class, the class foundation of the local file system implementation file storage.

For example, the following code will store uploaded files to /media/photos ignoring your Settings in MEDIA_ROOT:

from django.core.files.storage import FileSystemStorage
from django.db import models
​
fs = FileSystemStorage(location='/media/photos')
​
class Car(models.Model) :. photo = models.ImageField(storage=fs)Copy the code