当前位置: 首页>>代码示例>>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;未经允许,请勿转载。