最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Django文件存儲 默認存儲系統(tǒng)解析

 更新時間:2019年08月02日 10:02:37   作者:再見紫羅蘭  
這篇文章主要介紹了Django文件存儲 默認存儲系統(tǒng)解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下

Django默認使用的文件存儲系統(tǒng)'django.core.files.storage.FileSystemStorage'是一個本地存儲系統(tǒng),由settings中的DEFAULT_FILE_STORAGE值確定。

class FileSystemStorage(location=None, base_url=None, file_permissions_mode=None, directory_permissions_mode=None)

FileSystemStorage類繼承自Storage類,location是存儲文件的絕對路徑,默認值是settings中的MEDIA_ROOT值,base_url默認值是settings中的MEDIA_URL值。

當(dāng)定義location參數(shù)時,可以無視MEDIA_ROOT值來存儲文件:

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

這樣文件會存儲在/media/photos文件夾。

可以直接使用Django的文件存儲系統(tǒng)來存儲文件:

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

可以從FileSystemStorage類的_save方法看下上傳文件是怎么存儲的:

def _save(self, name, content):
  full_path = self.path(name)
 
  # Create any intermediate directories that do not exist.
  # Note that there is a race between os.path.exists and os.makedirs:
  # if os.makedirs fails with EEXIST, the directory was created
  # concurrently, and we can continue normally. Refs #16082.
  directory = os.path.dirname(full_path)
  if not os.path.exists(directory):
    try:
      if self.directory_permissions_mode is not None:
        # os.makedirs applies the global umask, so we reset it,
        # for consistency with file_permissions_mode behavior.
        old_umask = os.umask(0)
        try:
          os.makedirs(directory, self.directory_permissions_mode)
        finally:
          os.umask(old_umask)
      else:
        os.makedirs(directory)
    except OSError as e:
      if e.errno != errno.EEXIST:
        raise
  if not os.path.isdir(directory):
    raise IOError("%s exists and is not a directory." % directory)
 
  # There's a potential race condition between get_available_name and
  # saving the file; it's possible that two threads might return the
  # same name, at which point all sorts of fun happens. So we need to
  # try to create the file, but if it already exists we have to go back
  # to get_available_name() and try again.
 
  while True:
    try:
      # This file has a file path that we can move.
      if hasattr(content, 'temporary_file_path'):
        file_move_safe(content.temporary_file_path(), full_path)
 
      # This is a normal uploadedfile that we can stream.
      else:
        # This fun binary flag incantation makes os.open throw an
        # OSError if the file already exists before we open it.
        flags = (os.O_WRONLY | os.O_CREAT | os.O_EXCL |
             getattr(os, 'O_BINARY', 0))
        # The current umask value is masked out by os.open!
        fd = os.open(full_path, flags, 0o666)
        _file = None
        try:
          locks.lock(fd, locks.LOCK_EX)
          for chunk in content.chunks():
            if _file is None:
              mode = 'wb' if isinstance(chunk, bytes) else 'wt'
              _file = os.fdopen(fd, mode)
            _file.write(chunk)
        finally:
          locks.unlock(fd)
          if _file is not None:
            _file.close()
          else:
            os.close(fd)
    except OSError as e:
      if e.errno == errno.EEXIST:
        # Ooops, the file exists. We need a new file name.
        name = self.get_available_name(name)
        full_path = self.path(name)
      else:
        raise
    else:
      # OK, the file save worked. Break out of the loop.
      break
 
  if self.file_permissions_mode is not None:
    os.chmod(full_path, self.file_permissions_mode)
 
  # Store filenames with forward slashes, even on Windows.
  return force_text(name.replace('\\', '/'))

方法中可以看出,先判斷文件存儲的目錄是否存在,如果不存在,使用os.mkdirs()依次創(chuàng)建目錄。

根據(jù)directory_permissions_mode參數(shù)來確定創(chuàng)建的目錄的權(quán)限,應(yīng)該為(0777 &~umask)。

然后使用os.open()創(chuàng)建文件,flags參數(shù)為(os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, 'O_BINARY', 0)),

這樣當(dāng)文件已存在時,則報EEXIST異常,使用get_available_name()方法重新確定文件的名字。

mode為0o666,權(quán)限為(0666 &~umask)。

content為FILE對象,如一切正常,使用FILE.chunks()依次將內(nèi)容寫入文件。

最后,根據(jù)file_permissions_mode參數(shù),修改創(chuàng)建文件的權(quán)限。

相關(guān)文章

  • python 爬取疫情數(shù)據(jù)的源碼

    python 爬取疫情數(shù)據(jù)的源碼

    這篇文章主要介紹了python 爬取疫情數(shù)據(jù),,程序源碼簡單易懂,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-02-02
  • python tqdm用法及實例詳解

    python tqdm用法及實例詳解

    在本篇文章里小編給大家整理的是一篇關(guān)于python tqdm用法及實例詳解內(nèi)容,有需要的朋友們可以學(xué)習(xí)下。
    2021-06-06
  • 使用Python自制一個回收站清理器

    使用Python自制一個回收站清理器

    經(jīng)常筆記本電腦的回收站存儲了很多的文件,需要打開回收站全部選中進行清理。這篇文章將使用Python自制一個回收站清理器,需要的可以參考一下
    2023-03-03
  • python實現(xiàn)水印生成器

    python實現(xiàn)水印生成器

    這篇文章主要為大家詳細介紹了python實現(xiàn)水印生成器,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-05-05
  • python3+PyQt5使用數(shù)據(jù)庫表視圖

    python3+PyQt5使用數(shù)據(jù)庫表視圖

    這篇文章主要為大家詳細介紹了python3+PyQt5使用數(shù)據(jù)庫表視圖,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-04-04
  • Django獲取model中的字段名和字段的verbose_name方式

    Django獲取model中的字段名和字段的verbose_name方式

    這篇文章主要介紹了Django獲取model中的字段名和字段的verbose_name方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-05-05
  • python使用tkinter實現(xiàn)屏幕中間倒計時

    python使用tkinter實現(xiàn)屏幕中間倒計時

    這篇文章主要為大家詳細介紹了python使用tkinter實現(xiàn)屏幕中間倒計時,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-03-03
  • Pandas 處理DataFrame中的inf值實現(xiàn)

    Pandas 處理DataFrame中的inf值實現(xiàn)

    Inf 表示正無窮大或負無窮大,通常是在數(shù)學(xué)計算中產(chǎn)生的結(jié)果,本文主要介紹了Pandas 處理DataFrame中的inf值實現(xiàn),具有一定的參考價值,感興趣的可以了解一下
    2024-04-04
  • 基于Matplotlib?調(diào)用?pyplot?模塊中?figure()?函數(shù)處理?figure圖形對象

    基于Matplotlib?調(diào)用?pyplot?模塊中?figure()?函數(shù)處理?figure圖形對象

    這篇文章主要介紹了基于Matplotlib?調(diào)用?pyplot?模塊中?figure()?函數(shù)處理?figure圖形對象,matplotlib.pyplot模塊能夠快速地生成圖像,但如果使用面向?qū)ο蟮木幊趟枷?,我們就可以更好地控制和自定義圖像,下面就來詳細介紹其內(nèi)容,需要的朋友可以參考下
    2022-02-02
  • python 表達式和語句及for、while循環(huán)練習(xí)實例

    python 表達式和語句及for、while循環(huán)練習(xí)實例

    下面小編就為大家?guī)硪黄猵ython 表達式和語句及for、while循環(huán)練習(xí)實例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-07-07

最新評論

凤城市| 荆州市| 武安市| 水城县| 武邑县| 泽普县| 四子王旗| 长海县| 平原县| 纳雍县| 息烽县| 秦安县| 景宁| 敖汉旗| 盐城市| 崇阳县| 自贡市| 鹿邑县| 浦江县| 澄江县| 宜丰县| 洪泽县| 红河县| 景德镇市| 巨鹿县| 洪雅县| 扬州市| 龙川县| 双鸭山市| 甘孜县| 白城市| 罗江县| 周至县| 小金县| 静乐县| 安顺市| 天峨县| 江源县| 获嘉县| 攀枝花市| 偏关县|