Summary suspendedfc

position ease box interval due
front 2.50 2 1.00 2021-05-06T10:05:12Z

https://docs.djangoproject.com/en/3.1/ref/files/file/

The File class is a thin wrapper around a Python file object(File Object in Python) with some Django-specific additions. Internally, Django uses this class when it needs to represent a file. code

class File(file_object):
  pass

“file_object” is the underlying File Object in Python that this class wraps.

from django.core.files.base import File
stream = BytesIO() # stream or file like object
pdf_writer.write(stream)
page_obj.pdf.save(name=f"{page_num}.pdf",
                  content=File(stream))

ContentFile

The ContentFile class inherits from File, but unlike File it operates on string content (bytes also supported), rather than an actual file. For example:

from django.core.files.base import ContentFile
f1 = ContentFile("esta frase está en español")
f2 = ContentFile(b"these are bytes")
 # or
fh = open(original_file_path, "r")
file_content = ContentFile(fh.read())

#or

 #  ContentFile(b.getvalue())
 #   b = io.BytesIO()
 #   resized_photo.save(b, format=extension[1:])
 #   default_storage.save(book.cover_photo.path, ContentFile(b.getvalue()))
 def resize_book_photo_command(book: Book):
       logger.debug(f'Changing {book.title}')
       _, extension = os.path.splitext(book.cover_photo.path)
       photo = default_storage.open(book.cover_photo.path)
       resized_photo = Image.open(photo.file).resize((100, 100), Image.ANTIALIAS)
       b = io.BytesIO()
       resized_photo.save(b, format=extension[1:])
       resp = default_storage.save(book.cover_photo.path, ContentFile(b.getvalue()))
       book.cover_photo = os.path.join('books', os.path.basename(resp))
       book.save()
       logger.debug(f'Successfully saved {book.cover_photo}')

ImageFile

class ImageFile(file_object)[source]

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.

code link

from a1.models import Model1
from django.core.files.images import ImageFile
m = Model1.objects.create()
stream = open("1.png", "rb") # from file system
m.f1 = ImageFile(stream)
m.save()