91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Django文件存儲 默認存儲系統解析

發布時間:2020-09-21 05:41:02 來源:腳本之家 閱讀:160 作者:再見紫羅蘭 欄目:開發技術

Django默認使用的文件存儲系統'django.core.files.storage.FileSystemStorage'是一個本地存儲系統,由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值。

當定義location參數時,可以無視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的文件存儲系統來存儲文件:

>>> 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()依次創建目錄。

根據directory_permissions_mode參數來確定創建的目錄的權限,應該為(0777 &~umask)。

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

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

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

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

最后,根據file_permissions_mode參數,修改創建文件的權限。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

财经| 嘉荫县| 延安市| 崇义县| 马鞍山市| 乌苏市| 乌恰县| 玉溪市| 监利县| 孙吴县| 浦北县| 兴国县| 炎陵县| 丰宁| 利津县| 榆林市| 山阴县| 青州市| 鹿邑县| 廉江市| 沙坪坝区| 威信县| 亚东县| 永善县| 永德县| 崇州市| 湖州市| 长子县| 壤塘县| 石首市| 昌吉市| 胶南市| 兰坪| 阳西县| 临安市| 苗栗市| 巨野县| 乐清市| 荣昌县| 保山市| 长宁县|