파일 관리하기

이 문서는 Django의 유저에 의해 업로드된 파일에 접근하는 파일 접근 API를 설명합니다. The lower level API는 충분히 다른 목적으로 사용할 수 있을만큼 범용적입니다. 만약 《정적 파일》 (JS, CSS 등)을 관리하고 싶다면, :doc:`/howto/static-files/index`를 참고하세요.

기본값으로, Django는 MEDIA_ROOT`와 :setting:`MEDIA_URL 설정을 이용하여 파일을 로컬로 관리합니다. 아래 예시에서는 이러한 기본값을 이용한다고 가정합니다.

그러나, Django는 파일을 어디에, 어떻게 저장할지 완전히 커스터마이즈 할 수 있도록 커스텀 file storage systems 를 기록할 수 있는 방법을 제공합니다. 이 문서의 아래 절반은 이 저장 시스템이 어떻게 작동하는지 설명합니다.

모델에서 파일 다루기

FileField 또는 :class:`~django.db.models.ImageField`를 사용하는 경우, Django는 해당 파일을 다룰 때 사용할 수 있는 API를 제공합니다.

아래, 이미지를 저장하기 위해 :class:`~django.db.models.ImageField`를 사용하는 모델을 예로 들어봅시다:

from django.db import models

class Car(models.Model):
    name = models.CharField(max_length=255)
    price = models.DecimalField(max_digits=5, decimal_places=2)
    photo = models.ImageField(upload_to='cars')

모든 Car 인스턴스는 첨부된 사진에 대한 정보를 가져올 수 있는 photo 속성을 가지고 있을 것입니다:

>>> car = Car.objects.get(name="57 Chevy")
>>> car.photo
<ImageFieldFile: cars/chevy.jpg>
>>> car.photo.name
'cars/chevy.jpg'
>>> car.photo.path
'/media/cars/chevy.jpg'
>>> car.photo.url
'http://media.example.com/cars/chevy.jpg'

이 객체 –예시에서 car.photo–는 File 객체로서, 아래 나열된 메소드와 속성을 모두 가지고 있습니다.

주석

파일 저장은 모델을 데이터베이스에 저장하는 과정의 일부이기 때문에, 디스크에 저장되는 실제 파일명은 모델 저장이 끝나기 전까지는 확신할 수 없다.

예를 들어, name 속성을 바꿔 파일의 이름을 파일 저장소의 상대경로(만약 기본값으로 지정된 :class:`~django.core.files.storage.FileSystemStorage`를 사용하고 있다면, :setting:`MEDIA_ROOT`가 된다.)로 지정할 수 있다:

>>> import os
>>> from django.conf import settings
>>> initial_path = car.photo.path
>>> car.photo.name = 'cars/chevy_ii.jpg'
>>> new_path = settings.MEDIA_ROOT + car.photo.name
>>> # Move the file on the filesystem
>>> os.rename(initial_path, new_path)
>>> car.save()
>>> car.photo.path
'/media/cars/chevy_ii.jpg'
>>> car.photo.path == new_path
True

주석

While ImageField non-image data attributes, such as height, width, and size are available on the instance, the underlying image data cannot be used without reopening the image. For example:

>>> from PIL import Image
>>> car = Car.objects.get(name='57 Chevy')
>>> car.photo.width
191
>>> car.photo.height
287
>>> image = Image.open(car.photo)
# Raises ValueError: seek of closed file.
>>> car.photo.open()
<ImageFieldFile: cars/chevy.jpg>
>>> image = Image.open(car.photo)
>>> image
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=191x287 at 0x7F99A94E9048>

파일 객체

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

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

만약 File``을 직접 만들어야 한다면, 가장 쉬운 방법은 파이썬의 빌트인 ``file 객체를 활용하여 만드는 것입니다:

>>> from django.core.files import File

# Create a Python file object using open()
>>> f = open('/path/to/hello.world', 'w')
>>> myfile = File(f)

Now you can use any of the documented attributes and methods of 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:

>>> from django.core.files import File

# Create a Python file object using open() and the with statement
>>> with open('/path/to/hello.world', 'w') as f:
...     myfile = File(f)
...     myfile.write('Hello World')
...
>>> myfile.closed
True
>>> f.closed
True

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

OSError: [Errno 24] Too many open files

File storage

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

Django’s default file storage is given by the DEFAULT_FILE_STORAGE setting; if you don’t explicitly provide a storage system, this is the one that will be used.

See below for details of the built-in default file storage system, and see 커스텀 저장 시스템 작성하기 for information on writing your own file storage system.

Storage objects

Though most of the time you’ll want to use a File object (which delegates to the 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 more useful – you can use the 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

See File storage API for the file storage API.

The built-in filesystem storage class

Django ships with a django.core.files.storage.FileSystemStorage class which 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:

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)

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

Using a callable

New in Django 3.1.

You can use a callable as the storage parameter for FileField or ImageField. This allows you to modify the used storage at runtime, selecting different storages for different environments, for example.

Your callable will be evaluated when your models classes are loaded, and must return an instance of Storage.

예시:

from django.conf import settings
from django.db import models
from .storages import MyLocalStorage, MyRemoteStorage


def select_storage():
    return MyLocalStorage() if settings.DEBUG else MyRemoteStorage()


class MyModel(models.Model):
    my_file = models.FileField(storage=select_storage)