本文整理匯總了Python中django.core.files.uploadedfile.UploadedFile方法的典型用法代碼示例。如果您正苦於以下問題:Python uploadedfile.UploadedFile方法的具體用法?Python uploadedfile.UploadedFile怎麽用?Python uploadedfile.UploadedFile使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類django.core.files.uploadedfile
的用法示例。
在下文中一共展示了uploadedfile.UploadedFile方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: setUp
# 需要導入模塊: from django.core.files import uploadedfile [as 別名]
# 或者: from django.core.files.uploadedfile import UploadedFile [as 別名]
def setUp(self):
TestBase.setUp(self)
self._publish_transportation_form()
self._submit_transport_instance_w_attachment()
src = os.path.join(self.this_directory, "fixtures",
"transportation", "screenshot.png")
uf = UploadedFile(file=open(src), content_type='image/png')
count = MetaData.objects.count()
MetaData.media_upload(self.xform, uf)
self.assertEqual(MetaData.objects.count(), count + 1)
url = urljoin(
self.base_url,
reverse(profile, kwargs={'username': self.user.username})
)
self._logout()
self._create_user_and_login('deno', 'deno')
self.bc = BriefcaseClient(
username='bob', password='bob',
url=url,
user=self.user
)
示例2: clean
# 需要導入模塊: from django.core.files import uploadedfile [as 別名]
# 或者: from django.core.files.uploadedfile import UploadedFile [as 別名]
def clean(self, *args, **kwargs):
data = super(PrivateFileField, self).clean(*args, **kwargs)
file = data.file
if isinstance(file, UploadedFile):
# content_type is only available for uploaded files,
# and not for files which are already stored in the model.
content_type = file.content_type
if self.content_types and content_type not in self.content_types:
logger.debug('Rejected uploaded file type: %s', content_type)
raise ValidationError(self.error_messages['invalid_file_type'])
if self.max_file_size and file.size > self.max_file_size:
raise ValidationError(self.error_messages['file_too_large'].format(
max_size=filesizeformat(self.max_file_size),
size=filesizeformat(file.size)
))
return data
示例3: set_config_file
# 需要導入模塊: from django.core.files import uploadedfile [as 別名]
# 或者: from django.core.files.uploadedfile import UploadedFile [as 別名]
def set_config_file(key: str, file: UploadedFile):
from palanaeum.models import ConfigEntry
try:
entry = ConfigEntry.objects.get(key=key)
if entry.value:
os.unlink(os.path.join(settings.MEDIA_ROOT, entry.value))
except ConfigEntry.DoesNotExist:
entry = ConfigEntry(key=key)
except FileNotFoundError:
pass
file_path = os.path.join(settings.CONFIG_UPLOADS, file.name)
os.makedirs(settings.CONFIG_UPLOADS, exist_ok=True)
entry.value = os.path.relpath(file_path, settings.MEDIA_ROOT)
with open(file_path, mode='wb') as write_file:
for chunk in file.chunks():
write_file.write(chunk)
entry.save()
cache.set(key, entry.value)
return
示例4: normalize
# 需要導入模塊: from django.core.files import uploadedfile [as 別名]
# 或者: from django.core.files.uploadedfile import UploadedFile [as 別名]
def normalize(task_id, key, value):
try:
json.dumps(value)
return value
except TypeError:
if isinstance(value, models.Model):
return SimpleObjectSerializer().serialize([value]).pop()
elif isinstance(value, QuerySet):
return SimpleObjectSerializer().serialize(value)
elif isinstance(value, (dict, list, tuple, set)):
return pre_serialize(task_id, key, value)
elif isinstance(value, UploadedFile):
uploaded_file = value # type: UploadedFile
cache_key = str(task_id) + '__' + str(key) if key else str(task_id)
DbCache.put_to_db(cache_key, uploaded_file.read())
return {
'file_name': uploaded_file.name,
'cache_key': cache_key
}
return str(value)
示例5: test_upload_avatar_inTemp
# 需要導入模塊: from django.core.files import uploadedfile [as 別名]
# 或者: from django.core.files.uploadedfile import UploadedFile [as 別名]
def test_upload_avatar_inTemp(self):
avatar = open(image_path, "rb")
new_dict = default_dict2.copy()
new_dict['avatar'] = avatar
# all images are converted to jpg
new_file_name = os.path.basename(image_path).partition(".")[0]+".jpg"
avatar2 = UploadedFile(avatar, name=os.path.basename(image_path), content_type="image/png",
size=os.path.getsize(image_path))
response = self.client.post(reverse('user_profile:edit_profile', kwargs={"username": user_name}),
new_dict, follow=True)
# NOTE this doesn't verify whether the file has been uploaded successfully
self.assertContains(response, new_file_name)
self.delete_image_test()
avatar.close()
# helper function
示例6: test_resized_images_updated
# 需要導入模塊: from django.core.files import uploadedfile [as 別名]
# 或者: from django.core.files.uploadedfile import UploadedFile [as 別名]
def test_resized_images_updated(self):
"""
thumbnails should be updated if image is already present and updated when update_image=True
"""
assert self.profile.image
assert self.profile.image_small
assert self.profile.image_medium
# create a dummy image file in memory for upload
image_file = BytesIO()
image = Image.new('RGBA', size=(50, 50), color=(256, 0, 0))
image.save(image_file, 'png')
image_file.seek(0)
self.profile.image = UploadedFile(image_file, "filename.png", "image/png", len(image_file.getvalue()))
self.profile.save(update_image=True)
image_file_bytes = image_file.read()
assert self.profile.image_small.file.read() != image_file_bytes
assert self.profile.image_medium.file.read() != image_file_bytes
示例7: to_jsonable
# 需要導入模塊: from django.core.files import uploadedfile [as 別名]
# 或者: from django.core.files.uploadedfile import UploadedFile [as 別名]
def to_jsonable(self, cleaned_data):
data = {}
if isinstance(cleaned_data, UploadedFile):
data['filename'] = cleaned_data.name
data['size'] = cleaned_data.size
data['content-type'] = cleaned_data.content_type
data['charset'] = cleaned_data.charset
data['secret'] = new_file_secret()
h = hashlib.sha256()
for c in cleaned_data.chunks(1000):
h.update(c)
data['sha256'] = h.hexdigest()
return {'data': data, '_file': cleaned_data}
示例8: test_metadata_file_hash
# 需要導入模塊: from django.core.files import uploadedfile [as 別名]
# 或者: from django.core.files.uploadedfile import UploadedFile [as 別名]
def test_metadata_file_hash(self):
self._publish_transportation_form()
src = os.path.join(self.this_directory, "fixtures",
"transportation", "screenshot.png")
uf = UploadedFile(file=open(src), content_type='image/png')
count = MetaData.objects.count()
MetaData.media_upload(self.xform, uf)
# assert successful insert of new metadata record
self.assertEqual(MetaData.objects.count(), count + 1)
md = MetaData.objects.get(xform=self.xform,
data_value='screenshot.png')
# assert checksum string has been generated, hash length > 1
self.assertTrue(len(md.hash) > 16)
示例9: _json_write_to_file
# 需要導入模塊: from django.core.files import uploadedfile [as 別名]
# 或者: from django.core.files.uploadedfile import UploadedFile [as 別名]
def _json_write_to_file(parent, field, request, serializer):
json_serializer = serializer()
data = json_serializer.validate(request.data)
# create file object
with open(json_serializer.filenmame, 'wb+') as f:
in_memory_file = UploadedFile(
file=f,
name=json_serializer.filenmame,
content_type='application/json',
size=len(data.encode('utf-8')),
charset=None
)
# wrap and re-open file
file_obj = QueryDict('', mutable=True)
file_obj.update({'file': in_memory_file})
file_obj['file'].open()
file_obj['file'].seek(0)
file_obj['file'].write(data.encode('utf-8'))
serializer = RelatedFileSerializer(
data=file_obj,
content_types='application/json',
context={'request': request}
)
serializer.is_valid(raise_exception=True)
instance = serializer.create(serializer.validated_data)
setattr(parent, field, instance)
parent.save(update_fields=[field])
# Override 'file' return to hide storage details with stored filename
response = Response(RelatedFileSerializer(instance=instance, content_types='application/json').data)
response.data['file'] = instance.file.name
return response
示例10: save_uploaded_file
# 需要導入模塊: from django.core.files import uploadedfile [as 別名]
# 或者: from django.core.files.uploadedfile import UploadedFile [as 別名]
def save_uploaded_file(self, uploaded_file: UploadedFile):
save_path = pathlib.Path(settings.MEDIA_ROOT, 'sources', str(self.event_id), uploaded_file.name)
if save_path.exists():
save_path = save_path.with_name("{}_{}{}".format(save_path.name, time.time(), save_path.suffix))
save_path.parent.mkdir(parents=True, exist_ok=True, mode=0o775)
with open(str(save_path), mode='wb') as save_file:
for chunk in uploaded_file.chunks():
save_file.write(chunk)
self.file = str(save_path.relative_to(settings.MEDIA_ROOT))
return
示例11: zip_file1
# 需要導入模塊: from django.core.files import uploadedfile [as 別名]
# 或者: from django.core.files.uploadedfile import UploadedFile [as 別名]
def zip_file1(self):
return UploadedFile(open(os.path.join(settings.MEDIA_ROOT, "sample.zip"), 'r'))
示例12: zip_file2
# 需要導入模塊: from django.core.files import uploadedfile [as 別名]
# 或者: from django.core.files.uploadedfile import UploadedFile [as 別名]
def zip_file2(self):
return UploadedFile(open(os.path.join(settings.MEDIA_ROOT, "sample2.zip"), 'r'))
示例13: make_value_from_form
# 需要導入模塊: from django.core.files import uploadedfile [as 別名]
# 或者: from django.core.files.uploadedfile import UploadedFile [as 別名]
def make_value_from_form(self, value):
"""Convert a form value to a property value.
This extracts the content from the UploadedFile instance returned
by the FileField instance.
"""
if have_uploadedfile and isinstance(value, uploadedfile.UploadedFile):
if not self.form_value:
self.form_value = value.read()
b = db.Blob(self.form_value)
return b
return super(BlobProperty, self).make_value_from_form(value)
示例14: handle
# 需要導入模塊: from django.core.files import uploadedfile [as 別名]
# 或者: from django.core.files.uploadedfile import UploadedFile [as 別名]
def handle(self, *args, **options):
all_products = Product.objects.all()
for product in all_products:
if product.image:
image = UploadedFile(product.image.file, product.image.file.name)
product.cloudinary_image = image
product.save()
print(f"Product image for {product.name} migrated")
else:
print(f"No Product image for {product.name} to migrate")
示例15: _save
# 需要導入模塊: from django.core.files import uploadedfile [as 別名]
# 或者: from django.core.files.uploadedfile import UploadedFile [as 別名]
def _save(self, name, content):
name = self._normalise_name(name)
name = self._prepend_prefix(name)
content = UploadedFile(content, name)
response = self._upload(name, content)
return response['public_id']