當前位置: 首頁>>代碼示例>>Python>>正文


Python base.File方法代碼示例

本文整理匯總了Python中django.core.files.base.File方法的典型用法代碼示例。如果您正苦於以下問題:Python base.File方法的具體用法?Python base.File怎麽用?Python base.File使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在django.core.files.base的用法示例。


在下文中一共展示了base.File方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: listdir

# 需要導入模塊: from django.core.files import base [as 別名]
# 或者: from django.core.files.base import File [as 別名]
def listdir(self, name):
        name = self._normalize_name(self._clean_name(name))
        if name and not name.endswith('/'):
            name += '/'

        dirlist = bucket_lister(self.bucket_manager, self.bucket_name,
                                prefix=name)
        files = []
        dirs = set()
        base_parts = name.split("/")[:-1]
        for item in dirlist:
            parts = item['key'].split("/")
            parts = parts[len(base_parts):]
            if len(parts) == 1:
                # File
                files.append(parts[0])
            elif len(parts) > 1:
                # Directory
                dirs.add(parts[0])
        return list(dirs), files 
開發者ID:glasslion,項目名稱:django-qiniu-storage,代碼行數:22,代碼來源:backends.py

示例2: _create_empty_on_close

# 需要導入模塊: from django.core.files import base [as 別名]
# 或者: from django.core.files.base import File [as 別名]
def _create_empty_on_close(self):
        """
        Attempt to create an empty file for this key when this File is closed if no bytes
        have been written and no object already exists on S3 for this key.

        This behavior is meant to mimic the behavior of Django's builtin FileSystemStorage,
        where files are always created after they are opened in write mode:

            f = storage.open("file.txt", mode="w")
            f.close()
        """
        assert "w" in self._mode
        assert self._raw_bytes_written == 0

        try:
            # Check if the object exists on the server; if so, don't do anything
            self.obj.load()
        except ClientError as err:
            if err.response["ResponseMetadata"]["HTTPStatusCode"] == 404:
                self.obj.put(
                    Body=b"", **self._storage._get_write_parameters(self.obj.key)
                )
            else:
                raise 
開發者ID:jschneier,項目名稱:django-storages,代碼行數:26,代碼來源:s3boto3.py

示例3: _get_valid_path

# 需要導入模塊: from django.core.files import base [as 別名]
# 或者: from django.core.files.base import File [as 別名]
def _get_valid_path(s):
    # A blob name:
    #   * must not end with dot or slash
    #   * can contain any character
    #   * must escape URL reserved characters
    #     (not needed here since the azure client will do that)
    s = s.strip('./')
    if len(s) > _AZURE_NAME_MAX_LEN:
        raise ValueError(
            "File name max len is %d" % _AZURE_NAME_MAX_LEN)
    if not len(s):
        raise ValueError(
            "File name must contain one or more "
            "printable characters")
    if s.count('/') > 256:
        raise ValueError(
            "File name must not contain "
            "more than 256 slashes")
    return s


# Max len according to azure's docs 
開發者ID:jschneier,項目名稱:django-storages,代碼行數:24,代碼來源:azure_storage.py

示例4: __init__

# 需要導入模塊: from django.core.files import base [as 別名]
# 或者: from django.core.files.base import File [as 別名]
def __init__(self, credentials):
        """
        Initialize a Google Private sheets reader service, given a
        service account credentials JSON. The credentials can either
        be a dict, JSON string or file (bytes). This routine will do
        all the proper conversions for internal use.
        """
        # file upload, parsed
        if isinstance(credentials, bytes):
            credentials = json.loads(credentials.decode("utf-8"))
        elif isinstance(credentials, File):
            credentials = json.loads(credentials.read().decode("utf-8"))
        # JSON string, as stored in the DB
        elif isinstance(credentials, str):
            credentials = json.loads(credentials)
        # we need to have a decoded credentials dict by here
        creds = service_account.Credentials.from_service_account_info(
            credentials, scopes=self.SCOPES
        )
        # TODO: catch authentication error, return friendly msg. (we
        #       might we need to do this above as well)
        self.service = discovery.build("sheets", "v4", credentials=creds) 
開發者ID:propublica,項目名稱:django-collaborative,代碼行數:24,代碼來源:google_sheets.py

示例5: sendfile

# 需要導入模塊: from django.core.files import base [as 別名]
# 或者: from django.core.files.base import File [as 別名]
def sendfile(request, filepath, **kwargs):
    '''Use the SENDFILE_ROOT value composed with the path arrived as argument
    to build an absolute path with which resolve and return the file contents.

    If the path points to a file out of the root directory (should cover both
    situations with '..' and symlinks) then a 404 is raised.
    '''
    statobj = filepath.stat()

    # Respect the If-Modified-Since header.
    if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
                              statobj.st_mtime, statobj.st_size):
        return HttpResponseNotModified()

    with File(filepath.open('rb')) as f:
        response = HttpResponse(f.chunks())

    response["Last-Modified"] = http_date(statobj.st_mtime)
    return response 
開發者ID:moggers87,項目名稱:django-sendfile2,代碼行數:21,代碼來源:simple.py

示例6: add_view

# 需要導入模塊: from django.core.files import base [as 別名]
# 或者: from django.core.files.base import File [as 別名]
def add_view(self, request, form_url='', extra_context=None):
        # Prepopulate new configuration entries with the value of the current config, if given:
        if 'source' in request.GET:
            get = request.GET.copy()
            source_id = int(get.pop('source')[0])
            source = get_object_or_404(self.model, pk=source_id)
            source_dict = models.model_to_dict(source)
            for field_name, field_value in source_dict.items():
                # read files into request.FILES, if:
                # * user hasn't ticked the "clear" checkbox
                # * user hasn't uploaded a new file
                if field_value and isinstance(field_value, File):
                    clear_checkbox_name = '{0}-clear'.format(field_name)
                    if request.POST.get(clear_checkbox_name) != 'on':
                        request.FILES.setdefault(field_name, field_value)
                get[field_name] = field_value
            request.GET = get
        # Call our grandparent's add_view, skipping the parent code
        # because the parent code has a different way to prepopulate new configuration entries
        # with the value of the latest config, which doesn't make sense for keyed models.
        # pylint: disable=bad-super-call
        return super(ConfigurationModelAdmin, self).add_view(request, form_url, extra_context) 
開發者ID:duoduo369,項目名稱:weixin_server,代碼行數:24,代碼來源:admin.py

示例7: test_file_save_without_name

# 需要導入模塊: from django.core.files import base [as 別名]
# 或者: from django.core.files.base import File [as 別名]
def test_file_save_without_name(self):
        """
        File storage extracts the filename from the content object if no
        name is given explicitly.
        """
        self.assertFalse(self.storage.exists('test.file'))

        f = ContentFile('custom contents')
        f.name = 'test.file'

        storage_f_name = self.storage.save(None, f)

        self.assertEqual(storage_f_name, f.name)

        self.assertTrue(os.path.exists(os.path.join(self.temp_dir, f.name)))

        self.storage.delete(storage_f_name) 
開發者ID:nesdis,項目名稱:djongo,代碼行數:19,代碼來源:tests.py

示例8: test_listdir

# 需要導入模塊: from django.core.files import base [as 別名]
# 或者: from django.core.files.base import File [as 別名]
def test_listdir(self):
        """
        File storage returns a tuple containing directories and files.
        """
        self.assertFalse(self.storage.exists('storage_test_1'))
        self.assertFalse(self.storage.exists('storage_test_2'))
        self.assertFalse(self.storage.exists('storage_dir_1'))

        self.storage.save('storage_test_1', ContentFile('custom content'))
        self.storage.save('storage_test_2', ContentFile('custom content'))
        os.mkdir(os.path.join(self.temp_dir, 'storage_dir_1'))

        dirs, files = self.storage.listdir('')
        self.assertEqual(set(dirs), {'storage_dir_1'})
        self.assertEqual(set(files), {'storage_test_1', 'storage_test_2'})

        self.storage.delete('storage_test_1')
        self.storage.delete('storage_test_2')
        os.rmdir(os.path.join(self.temp_dir, 'storage_dir_1')) 
開發者ID:nesdis,項目名稱:djongo,代碼行數:21,代碼來源:tests.py

示例9: __hash__

# 需要導入模塊: from django.core.files import base [as 別名]
# 或者: from django.core.files.base import File [as 別名]
def __hash__(self):
        return hash(self.name)

    # The standard File contains most of the necessary properties, but
    # FieldFiles can be instantiated without a name, so that needs to
    # be checked for here. 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:8,代碼來源:files.py

示例10: get_prep_value

# 需要導入模塊: from django.core.files import base [as 別名]
# 或者: from django.core.files.base import File [as 別名]
def get_prep_value(self, value):
        "Returns field's value prepared for saving into a database."
        value = super(FileField, self).get_prep_value(value)
        # Need to convert File objects provided via a form to unicode for database insertion
        if value is None:
            return None
        return six.text_type(value) 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:9,代碼來源:files.py

示例11: _set_name

# 需要導入模塊: from django.core.files import base [as 別名]
# 或者: from django.core.files.base import File [as 別名]
def _set_name(self, name):
        # Sanitize the file name so that it can't be dangerous.
        if name is not None:
            # Just use the basename of the file -- anything else is dangerous.
            name = os.path.basename(name)

            # File names longer than 255 characters can cause problems on older OSes.
            if len(name) > 255:
                name, ext = os.path.splitext(name)
                ext = ext[:255]
                name = name[:255 - len(ext)] + ext

        self._name = name 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:15,代碼來源:uploadedfile.py

示例12: test_media_file_hash

# 需要導入模塊: from django.core.files import base [as 別名]
# 或者: from django.core.files.base import File [as 別名]
def test_media_file_hash(self):
        name = "screenshot.png"
        media_file = os.path.join(
            self.this_directory, 'fixtures', 'transportation', name)
        m = MetaData.objects.create(
            data_type='media', xform=self.xform, data_value=name,
            data_file=File(open(media_file), name),
            data_file_type='image/png')
        f = open(media_file)
        media_hash = 'md5:%s' % hashlib.md5(f.read()).hexdigest()
        f.close()
        meta_hash = m.hash
        self.assertEqual(meta_hash, media_hash)
        self.assertEqual(m.file_hash, media_hash) 
開發者ID:awemulya,項目名稱:kobo-predict,代碼行數:16,代碼來源:test_form_metadata.py

示例13: setUp

# 需要導入模塊: from django.core.files import base [as 別名]
# 或者: from django.core.files.base import File [as 別名]
def setUp(self):
        super(self.__class__, self).setUp()
        self._publish_transportation_form_and_submit_instance()
        self.media_file = "1335783522563.jpg"
        media_file = os.path.join(
            self.this_directory, 'fixtures',
            'transportation', 'instances', self.surveys[0], self.media_file)
        self.instance = Instance.objects.all()[0]
        self.attachment = Attachment.objects.create(
            instance=self.instance,
            media_file=File(open(media_file), media_file)) 
開發者ID:awemulya,項目名稱:kobo-predict,代碼行數:13,代碼來源:test_attachment.py

示例14: get_prep_value

# 需要導入模塊: from django.core.files import base [as 別名]
# 或者: from django.core.files.base import File [as 別名]
def get_prep_value(self, value):
        value = super().get_prep_value(value)
        # Need to convert File objects provided via a form to string for database insertion
        if value is None:
            return None
        return str(value) 
開發者ID:reBiocoder,項目名稱:bioforum,代碼行數:8,代碼來源:files.py

示例15: write

# 需要導入模塊: from django.core.files import base [as 別名]
# 或者: from django.core.files.base import File [as 別名]
def write(self, content):
        if 'w' not in self._mode:
            raise AttributeError("File was opened for read-only access.")

        self.file.write(force_bytes(content))
        self._is_dirty = True
        self._is_read = True 
開發者ID:glasslion,項目名稱:django-qiniu-storage,代碼行數:9,代碼來源:backends.py


注:本文中的django.core.files.base.File方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。