Temporaryuploadedfile Python How to Verify That File Upload Django
Python django.core.files.uploadedfile.TemporaryUploadedFile() Examples
The post-obit are 13 lawmaking examples for showing how to employ django.core.files.uploadedfile.TemporaryUploadedFile() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you lot don't like, and go to the original project or source file by post-obit the links to a higher place each example.
You lot may check out the related API usage on the sidebar.
You may besides want to check out all bachelor functions/classes of the module django.core.files.uploadedfile , or endeavor the search function .
Case 1
def salvage(self, commit=Truthful, use_card_filenames=False): instance = super(TinyPngForm, self).save(commit=Imitation) for field in self.fields.keys(): if (hasattr(case, field) and field in dir(self.Meta.model) and blazon(self.Meta.model._meta.get_field(field)) == models.models.ImageField): image = self.cleaned_data[field] if image and (isinstance(prototype, InMemoryUploadedFile) or isinstance(epitome, TemporaryUploadedFile)): filename = paradigm.proper noun _, extension = os.path.splitext(filename) if extension.lower() == '.png': paradigm = shrinkImageFromData(paradigm.read(), filename) if use_card_filenames and field in models.cardsImagesToName: epitome.name = models.cardsImagesToName[field]({ 'id': case.id, 'firstname': instance.idol.name.dissever(' ')[-1] if instance.idol and instance.idol.name else 'Unknown', }) else: prototype.name = randomString(32) + extension setattr(instance, field, epitome) if commit: instance.save() return instance
Example ii
def _tinypng_images(self, validated_data): idolName = cocky.context['request'].information.get('idol', None) if not idolName: idolName = self.instance.idol.name idolId = validated_data['id'] if 'id' in validated_data else self.instance.id for (field, value) in validated_data.items(): if value and (isinstance(value, InMemoryUploadedFile) or isinstance(value, TemporaryUploadedFile)): filename = value.name value = shrinkImageFromData(value.read(), filename) validated_data[field] = value if field in models.cardsImagesToName: value.proper noun = models.cardsImagesToName[field]({ 'id': idolId, 'firstname': idolName.split(' ')[-1] if idolName else 'Unknown', }) return validated_data
Instance three
def __setstate__(self, pickle_dictionary): if pickle_dictionary["_context"]["type"] == "file.content" and \ isinstance(pickle_dictionary["_context"]["value"], dict): arguments = pickle_dictionary["_context"]["value"] # File data info, especially useful for exam pickling self.base64_file_data_len = len(arguments["content"]) file_content = base64.b64decode(arguments.pop("content")) # File information info, especially useful for test pickling self.file_data_len = len(file_content) file_object = TemporaryUploadedFile(**arguments) file_object.write(file_content) file_object.flush() pickle_dictionary["_context"]["value"] = file_object self.__dict__.update(pickle_dictionary)
Example 4
def temporary_uploaded_file(): def inner(filename, content): fp = uploadedfile.TemporaryUploadedFile( name=filename + ".tempfile", content_type='text/plain', size=0, charset='utf8', ) fp.write(content) fp.flush() return fp return inner
Case v
def process_zip(self): with file_storage.get_document_as_local_fn(self.source_path) as (local_file_path, _): with zipfile.ZipFile(local_file_path) every bit zip_file: zip_file_filelist = zip_file.filelist self.log_info('Start extracting {} documents from {}'.format( len(zip_file_filelist), local_file_path)) for n, a_file in enumerate(zip_file_filelist): if a_file.is_dir(): continue file_size = a_file.file_size file_name = bone.path.basename(a_file.filename) mime_type = cocky.get_mime_type(file_name) self.log_info( 'Extract/start LoadDocument for {} of {} files: proper name={}, size={}, mime_type={}'.format( n + 1, len(zip_file_filelist), file_name, file_size, mime_type)) with TemporaryUploadedFile(file_name, mime_type, file_size, 'utf-viii') every bit tempfile: tempfile.file = zip_file.open(a_file) tempfile.file.seek = lambda *args: 0 self.upload_file( file_name=file_name, file_size=file_size, contents=tempfile, directory_path=cocky.directory_path)
Example 6
def process_tar(self): with file_storage.get_document_as_local_fn(cocky.source_path) as (local_file_path, _): with tarfile.TarFile(local_file_path) every bit tar_file: tar_file_members = tar_file.getmembers() self.log_info('Start extracting {} documents from {}'.format( len(tar_file_members), local_file_path)) for n, a_file in enumerate(tar_file_members): if a_file.isdir(): continue file_size = a_file.size file_name = os.path.basename(a_file.proper noun) mime_type = self.get_mime_type(file_name) cocky.log_info( 'Extract/outset LoadDocument for {} of {} files: name={}, size={}, mime_type={}'.format( n + 1, len(tar_file_members), file_name, file_size, mime_type)) with TemporaryUploadedFile(file_name, mime_type, file_size, 'utf-8') as tempfile: tempfile.file = tar_file.extractfile(a_file) cocky.upload_file( file_name=file_name, file_size=file_size, contents=tempfile, directory_path=self.directory_path)
Example vii
def temporary_uploaded_file(): def inner(filename, content): fp = uploadedfile.TemporaryUploadedFile( name=filename + '.tempfile', content_type='text/plain', size=0, charset='utf8', ) fp.write(content) fp.affluent() return fp return inner
Example 8
def validate(self, data): if self.context['request'].method == 'POST' and ('idol' non in cocky.context['request'].data or not self.context['request'].data['idol']): heighten serializers.ValidationError({ 'idol': ['This field is required.'], }) for (field, value) in data.items(): if value and (isinstance(value, InMemoryUploadedFile) or isinstance(value, TemporaryUploadedFile)): _, extension = os.path.splitext(value.name) if extension.lower() != '.png': heighten serializers.ValidationError({ field: ['Simply png images are accepted.'], }) return information
Example nine
def clean_file(self): file = self.cleaned_data['file'] if not magic: heighten forms.ValidationError(_("The file could non be validated")) # Won't ever raise. Has at most one '.' so lstrip is fine here ext = os.path.splitext(file.proper noun)[1].lstrip('.').lower() if ext not in settings.ST_ALLOWED_UPLOAD_FILE_MEDIA_TYPE: raise forms.ValidationError( _("Unsupported file extension %(extension)south. " "Supported extensions are %(supported)southward.") % { 'extension': ext, 'supported': ", ".join( sorted(settings.ST_ALLOWED_UPLOAD_FILE_MEDIA_TYPE.keys()))}) try: if isinstance(file, TemporaryUploadedFile): file_mime = magic.from_file(file.temporary_file_path(), mime=Truthful) else: # In-retention file file_mime = magic.from_buffer(file.read(), mime=Truthful) except magic.MagicException as east: logger.exception(due east) raise forms.ValidationError(_("The file could not be validated")) mime = settings.ST_ALLOWED_UPLOAD_FILE_MEDIA_TYPE.get(ext, None) if mime != file_mime: raise forms.ValidationError( _("Unsupported file mime type %(mime)s. " "Supported types are %(supported)s.") % { 'mime': file_mime, 'supported': ", ".join( sorted(settings.ST_ALLOWED_UPLOAD_FILE_MEDIA_TYPE.values()))}) return file
Instance 10
def new_file(cocky, file_name, *args, **kwargs): """ Create the file object to append to every bit information is coming in. """ super(TemporaryFileUploadHandler, self).new_file(file_name, *args, **kwargs) self.file = TemporaryUploadedFile(self.file_name, self.content_type, 0, self.charset)
Instance eleven
def test_move_temporary_file(self): """ The temporary uploaded file is moved rather than copied to the destination. """ with TemporaryUploadedFile('something.txt', 'text/plain', 0, 'UTF-eight') as tmp_file: tmp_file_path = tmp_file.temporary_file_path() Certificate.objects.create(myfile=tmp_file) cocky.assertFalse(os.path.exists(tmp_file_path), 'Temporary file nonetheless exists')
Case 12
def test_move_temporary_file(self): """ The temporary uploaded file is moved rather than copied to the destination. """ with TemporaryUploadedFile('something.txt', 'text/manifestly', 0, 'UTF-eight') as tmp_file: tmp_file_path = tmp_file.temporary_file_path() Certificate.objects.create(myfile=tmp_file) self.assertFalse(os.path.exists(tmp_file_path), 'Temporary file nevertheless exists')
Example xiii
def test_file_context(self): response = None with open up("threats/test_data/boss.gif", "rb") as boss_reader: file_data = boss_reader.read() boss_reader.seek(0) response = self.client.mail service( '/', {'artifact': '{"type": "file.content"}', 'file': boss_reader}, format="multipart" ) upload_file_args = { "name": "dominate.gif", "content_type": "awarding/octet-stream", "size": 29927, "charset": None, } cocky.assertEqual(response.status_code, 200) temp_file = TemporaryUploadedFile(**upload_file_args) temp_file.write(file_data) temp_file.flush() context = SearchContext({"type": "file.content", "value": temp_file}) context.save() self.assertEqual(context.file_data_len, len(file_data)) loaded_context = SearchContext.load(context.id) self.assertEqual(loaded_context.base64_file_data_len, context.base64_file_data_len) self.assertEqual(loaded_context.file_data_len, context.file_data_len) with open(loaded_context.value.temporary_file_path(), "rb") as temp_file: loaded_file_data = temp_file.read() for counter in range(0, len(loaded_file_data) // 100): begin = counter * 100 end = brainstorm + 100 self.assertEqual(file_data[brainstorm:terminate], loaded_file_data[begin:end]) self.assertEqual(len(file_data), len(loaded_file_data))
Source: https://www.programcreek.com/python/example/52486/django.core.files.uploadedfile.TemporaryUploadedFile
0 Response to "Temporaryuploadedfile Python How to Verify That File Upload Django"
Post a Comment