def wrap(self, **kargs): result = {} if kargs: files = {} for (key, value) in kargs.items(): if key.endswith('.name'): realkey = key[:-5] realvalue = 'name' elif key.endswith('.path'): realkey = key[:-5] realvalue = 'path' elif key.endswith('.content_type'): # not used realkey = key[:-13] realvalue = 'type' else: raise ValidationError("invalid body") files.setdefault(realkey, {}) files[realkey][realvalue] = value for symbol, data in files.items(): # nginx file_path = get_random_path(None, data['name']) file_path += get_extension(data['type'], data['name']) os.rename(data['path'], os.sep.join((settings.MEDIA_ROOT, file_path))) result[symbol] = file_path else: for request_file in self.request.files: target_file = self.request.files[request_file][0] name_with_ext = target_file['filename'] + get_extension( target_file['content_type'], target_file['filename']) result[request_file] = File(ContentFile(target_file['body']), name=name_with_ext) return fn(self, result)
def download_http_photo(self, url, user_profile): if url is not None: try: response = urlopen(url) filename = get_random_path(None, url.split('/')[-1]) content = ContentFile(response.read()) user_profile.photo.save(filename, content, False) except Exception as e: self.logger.error( "Unable to download photo from url %s for user %s because %s", url, user_profile.username, e)
def rename(self, obj, attr): field = getattr(obj, attr) if field: path = field.path if not os.path.isfile(path): return print(path) mime = subprocess.Popen( "/usr/bin/file -b --mime-type {}".format(path), shell=True, stdout=subprocess.PIPE).communicate()[0] if isinstance(mime, bytes): # py2 py3 support mime = mime.decode('utf-8') ext_base = mime.split('/') if len(ext_base) == 2: ext = "".join(('x.', ext_base[1].strip())) else: ext = 'x' new_name = get_random_path(None, ext) new_path = os.sep.join((os.path.dirname(path), new_name)) os.rename(path, new_path) field.name = new_name obj.save()