本文整理汇总了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
示例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
示例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
示例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)
示例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
示例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)
示例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)
示例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'))
示例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.
示例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)
示例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
示例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)
示例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))
示例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)
示例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