Python mimetypes.guess_extension() Examples
The following are 30
code examples of mimetypes.guess_extension().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
mimetypes
, or try the search function
.
Example #1
Source File: telegram.py From fishroom with GNU General Public License v3.0 | 8 votes |
def upload_audio(self, file_id, mime): if not self.file_store: return None, "No file store available" filedata = self.download_file(file_id) if filedata is None: return None, "teleboto Faild to download file" if mime is None: mime = magic.from_buffer(filedata, mime=True).decode('utf-8') ext = mimetypes.guess_extension(mime) if ext is None: raise Exception("Failed to guess ext from mime: %s" % mime) filename = "voice" + ext url = self.file_store.upload_file(filedata, filename, filetype="audio") if url is None: return None, "Failed to upload Document" return url, None
Example #2
Source File: shared.py From janeway with GNU Affero General Public License v3.0 | 6 votes |
def guess_extension(mime): """ This function gets extensions from mimes, and if it can't find it uses the standard guesses :param mime: a mimetype string :return: a string containing a file extension eg. doc or docx """ if mime == 'text/plain': extension = 'txt' elif mime == 'application/msword': extension = 'doc' elif mime == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': extension = 'docx' elif mime == 'application/vnd.oasis.opendocument.text': extension = 'odt' elif mime == 'text/html;charset=UTF-8': extension = 'html' else: extension = mimetypes.guess_extension(mime) return extension
Example #3
Source File: stdfmemail.py From HomePWN with GNU General Public License v3.0 | 6 votes |
def _savePartToFile(self, messagePart): fn = messagePart.get_filename() counter = 0 if not fn: ext = mimetypes.guess_extension(messagePart.get_content_type()) # Bug in python returns .ksh for text/plain. Wait for python fix? if not ext: # generic extension? ext = '.bin' fn = 'emailpart%s' % (ext) fn = os.path.basename(fn) # Sanitize Filename. attempted_filename = fn while os.path.exists(os.path.join(self.DOWNLOAD_DIR, attempted_filename)): counter += 1 attempted_filename = "%s%s%s" % (os.path.splitext(fn)[0], counter, os.path.splitext(fn)[1]) fn = attempted_filename fqfn = os.path.join(self.DOWNLOAD_DIR, fn) if messagePart.get_content_maintype() == "text": with open(fqfn, 'w') as f: f.write(messagePart.get_payload(decode=True)) else: with open(fqfn, 'wb') as f: f.write(messagePart.get_payload(decode=True))
Example #4
Source File: screenshot.py From libvirt-test-API with GNU General Public License v2.0 | 6 votes |
def screenshot(params): """This method takes a screenshot of a running machine and saves it in a filename""" ret = 1 logger = params['logger'] conn = sharedmod.libvirtobj['conn'] dom = conn.lookupByName(params['guestname']) st = conn.newStream(0) screen = params.get('screen', 0) mime = dom.screenshot(st, int(screen), 0) ext = mimetypes.guess_extension(mime) or '.ppm' last_filename = params['filename'] + ext f = open(last_filename, 'wb') logger.debug('Saving screenshot into %s' % last_filename) st.recvAll(saver, f) logger.debug('Mimetype of the file is %s' % mime) ret = st.finish() return ret
Example #5
Source File: sonofmmm.py From aws-extender with MIT License | 6 votes |
def __init__(self, config_file=None): super(SonOfMMM, self).__init__(config_file) self.log_file = '%s.log' % self.instance_id self.log_path = os.path.join(self.working_dir, self.log_file) boto.set_file_logger(self.name, self.log_path) if self.sd.has_option('ffmpeg_args'): self.command = '/usr/local/bin/ffmpeg ' + self.sd.get('ffmpeg_args') else: self.command = '/usr/local/bin/ffmpeg -y -i %s %s' self.output_mimetype = self.sd.get('output_mimetype') if self.sd.has_option('output_ext'): self.output_ext = self.sd.get('output_ext') else: self.output_ext = mimetypes.guess_extension(self.output_mimetype) self.output_bucket = self.sd.get_obj('output_bucket') self.input_bucket = self.sd.get_obj('input_bucket') # check to see if there are any messages queue # if not, create messages for all files in input_bucket m = self.input_queue.read(1) if not m: self.queue_files()
Example #6
Source File: download.py From rules_pip with MIT License | 6 votes |
def _get_http_response_filename(resp, link): # type: (Response, Link) -> str """Get an ideal filename from the given HTTP response, falling back to the link filename if not provided. """ filename = link.filename # fallback # Have a look at the Content-Disposition header for a better guess content_disposition = resp.headers.get('content-disposition') if content_disposition: filename = parse_content_disposition(content_disposition, filename) ext = splitext(filename)[1] # type: Optional[str] if not ext: ext = mimetypes.guess_extension( resp.headers.get('content-type', '') ) if ext: filename += ext if not ext and link.url != resp.url: ext = os.path.splitext(resp.url)[1] if ext: filename += ext return filename
Example #7
Source File: 12-parse-email.py From xd with MIT License | 6 votes |
def generate_email_files(msg): counter = 1 upload_date = time.mktime(email.utils.parsedate(msg["Date"])) for part in msg.walk(): # multipart/* are just containers if part.get_content_maintype() == 'multipart': continue # Applications should really sanitize the given filename so that an # email message can't be used to overwrite important files filename = part.get_filename() if not filename: ext = mimetypes.guess_extension(part.get_content_type()) if not ext: # Use a generic bag-of-bits extension ext = '.bin' filename = 'part-%03d%s' % (counter, ext) counter += 1 data = part.get_payload(decode=True) if parse_pathname(filename).ext == '.zip': for zipfn, zipdata, zipdt in generate_zip_files(data): yield zipfn, zipdata, zipdt else: yield filename, data, upload_date
Example #8
Source File: test_data_files.py From OasisPlatform with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_data_file_is_uploaded___file_can_be_retrieved(self, file_content, content_type): with TemporaryDirectory() as d: with override_settings(MEDIA_ROOT=d): user = fake_user() cmf = fake_data_file() self.app.post( cmf.get_absolute_data_file_url(), headers={ 'Authorization': 'Bearer {}'.format(AccessToken.for_user(user)) }, upload_files=( ('file', 'file{}'.format(mimetypes.guess_extension(content_type)), file_content), ), ) response = self.app.get( cmf.get_absolute_data_file_url(), headers={ 'Authorization': 'Bearer {}'.format(AccessToken.for_user(user)) }, ) self.assertEqual(response.body, file_content) self.assertEqual(response.content_type, content_type)
Example #9
Source File: test_portfolio.py From OasisPlatform with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_accounts_file_is_uploaded___file_can_be_retrieved(self, file_content, content_type): with TemporaryDirectory() as d: with override_settings(MEDIA_ROOT=d): user = fake_user() portfolio = fake_portfolio() self.app.post( portfolio.get_absolute_accounts_file_url(), headers={ 'Authorization': 'Bearer {}'.format(AccessToken.for_user(user)) }, upload_files=( ('file', 'file{}'.format(mimetypes.guess_extension(content_type)), file_content), ), ) response = self.app.get( portfolio.get_absolute_accounts_file_url(), headers={ 'Authorization': 'Bearer {}'.format(AccessToken.for_user(user)) }, ) self.assertEqual(response.body, file_content) self.assertEqual(response.content_type, content_type)
Example #10
Source File: test_portfolio.py From OasisPlatform with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_location_file_is_uploaded___file_can_be_retrieved(self, file_content, content_type): with TemporaryDirectory() as d: with override_settings(MEDIA_ROOT=d): user = fake_user() portfolio = fake_portfolio() self.app.post( portfolio.get_absolute_location_file_url(), headers={ 'Authorization': 'Bearer {}'.format(AccessToken.for_user(user)) }, upload_files=( ('file', 'file{}'.format(mimetypes.guess_extension(content_type)), file_content), ), ) response = self.app.get( portfolio.get_absolute_location_file_url(), headers={ 'Authorization': 'Bearer {}'.format(AccessToken.for_user(user)) }, ) self.assertEqual(response.body, file_content) self.assertEqual(response.content_type, content_type)
Example #11
Source File: test_portfolio.py From OasisPlatform with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_reinsurance_scope_file_is_uploaded___file_can_be_retrieved(self, file_content, content_type): with TemporaryDirectory() as d: with override_settings(MEDIA_ROOT=d): user = fake_user() portfolio = fake_portfolio() self.app.post( portfolio.get_absolute_reinsurance_scope_file_url(), headers={ 'Authorization': 'Bearer {}'.format(AccessToken.for_user(user)) }, upload_files=( ('file', 'file{}'.format(mimetypes.guess_extension(content_type)), file_content), ), ) response = self.app.get( portfolio.get_absolute_reinsurance_scope_file_url(), headers={ 'Authorization': 'Bearer {}'.format(AccessToken.for_user(user)) }, ) self.assertEqual(response.body, file_content) self.assertEqual(response.content_type, content_type)
Example #12
Source File: test_portfolio.py From OasisPlatform with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_reinsurance_info_file_is_uploaded___file_can_be_retrieved(self, file_content, content_type): with TemporaryDirectory() as d: with override_settings(MEDIA_ROOT=d): user = fake_user() portfolio = fake_portfolio() self.app.post( portfolio.get_absolute_reinsurance_info_file_url(), headers={ 'Authorization': 'Bearer {}'.format(AccessToken.for_user(user)) }, upload_files=( ('file', 'file{}'.format(mimetypes.guess_extension(content_type)), file_content), ), ) response = self.app.get( portfolio.get_absolute_reinsurance_info_file_url(), headers={ 'Authorization': 'Bearer {}'.format(AccessToken.for_user(user)) }, ) self.assertEqual(response.body, file_content) self.assertEqual(response.content_type, content_type)
Example #13
Source File: helpers.py From followthemoney with MIT License | 6 votes |
def entity_filename(proxy, base_name=None, extension=None): """Derive a safe filename for the given entity.""" if proxy.schema.is_a('Document'): for extension_ in proxy.get('extension', quiet=True): if extension is not None: break extension = extension_ for file_name in proxy.get('fileName', quiet=True): base_name_, extension_ = splitext(file_name) if base_name is None and len(base_name_): base_name = base_name_ if extension is None and len(extension_): extension = extension_ for mime_type in proxy.get('mimeType', quiet=True): if extension is not None: break extension = guess_extension(mime_type) base_name = base_name or proxy.id return safe_filename(base_name, extension=extension)
Example #14
Source File: utils.py From Telethon with MIT License | 6 votes |
def get_extension(media): """Gets the corresponding extension for any Telegram media.""" # Photos are always compressed as .jpg by Telegram try: get_input_photo(media) return '.jpg' except TypeError: # These cases are not handled by input photo because it can't if isinstance(media, (types.UserProfilePhoto, types.ChatPhoto)): return '.jpg' # Documents will come with a mime type if isinstance(media, types.MessageMediaDocument): media = media.document if isinstance(media, ( types.Document, types.WebDocument, types.WebDocumentNoProxy)): if media.mime_type == 'application/octet-stream': # Octet stream are just bytes, which have no default extension return '' else: return guess_extension(media.mime_type) or '' return ''
Example #15
Source File: util.py From AstroBox with GNU Affero General Public License v3.0 | 6 votes |
def get_filename(self, content_type): if not self._basename: return None typeValue = map(str.strip, content_type.split(";")) if len(typeValue) == 0: return None extension = mimetypes.guess_extension(typeValue[0]) if not extension: return None return "%s%s" % (self._basename, extension) #~~ admin access validator for use with tornado
Example #16
Source File: AttachBase.py From apprise with MIT License | 6 votes |
def name(self): """ Returns the filename """ if self._name: # return our fixed content return self._name if not self.exists(): # we could not obtain our name return None if not self.detected_name: # If we get here, our download was successful but we don't have a # filename based on our content. extension = mimetypes.guess_extension(self.mimetype) self.detected_name = '{}{}'.format( self.unknown_filename, extension if extension else self.unknown_filename_extension) return self.detected_name
Example #17
Source File: upload.py From zulip with Apache License 2.0 | 6 votes |
def get_file_info(request: HttpRequest, user_file: File) -> Tuple[str, int, Optional[str]]: uploaded_file_name = user_file.name content_type = request.GET.get('mimetype') if content_type is None: guessed_type = guess_type(uploaded_file_name)[0] if guessed_type is not None: content_type = guessed_type else: extension = guess_extension(content_type) if extension is not None: uploaded_file_name = uploaded_file_name + extension uploaded_file_name = urllib.parse.unquote(uploaded_file_name) uploaded_file_size = user_file.size return uploaded_file_name, uploaded_file_size, content_type
Example #18
Source File: stdfmemail.py From apple_bleee with GNU General Public License v3.0 | 6 votes |
def _savePartToFile(self, messagePart): fn = messagePart.get_filename() counter = 0 if not fn: ext = mimetypes.guess_extension(messagePart.get_content_type()) # Bug in python returns .ksh for text/plain. Wait for python fix? if not ext: # generic extension? ext = '.bin' fn = 'emailpart%s' % (ext) fn = os.path.basename(fn) # Sanitize Filename. attempted_filename = fn while os.path.exists(os.path.join(self.DOWNLOAD_DIR, attempted_filename)): counter += 1 attempted_filename = "%s%s%s" % (os.path.splitext(fn)[0], counter, os.path.splitext(fn)[1]) fn = attempted_filename fqfn = os.path.join(self.DOWNLOAD_DIR, fn) if messagePart.get_content_maintype() == "text": with open(fqfn, 'w') as f: f.write(messagePart.get_payload(decode=True)) else: with open(fqfn, 'wb') as f: f.write(messagePart.get_payload(decode=True))
Example #19
Source File: download.py From pipenv with MIT License | 6 votes |
def _get_http_response_filename(resp, link): # type: (Response, Link) -> str """Get an ideal filename from the given HTTP response, falling back to the link filename if not provided. """ filename = link.filename # fallback # Have a look at the Content-Disposition header for a better guess content_disposition = resp.headers.get('content-disposition') if content_disposition: filename = parse_content_disposition(content_disposition, filename) ext = splitext(filename)[1] # type: Optional[str] if not ext: ext = mimetypes.guess_extension( resp.headers.get('content-type', '') ) if ext: filename += ext if not ext and link.url != resp.url: ext = os.path.splitext(resp.url)[1] if ext: filename += ext return filename
Example #20
Source File: download.py From pex with Apache License 2.0 | 6 votes |
def _get_http_response_filename(resp, link): # type: (Response, Link) -> str """Get an ideal filename from the given HTTP response, falling back to the link filename if not provided. """ filename = link.filename # fallback # Have a look at the Content-Disposition header for a better guess content_disposition = resp.headers.get('content-disposition') if content_disposition: filename = parse_content_disposition(content_disposition, filename) ext = splitext(filename)[1] # type: Optional[str] if not ext: ext = mimetypes.guess_extension( resp.headers.get('content-type', '') ) if ext: filename += ext if not ext and link.url != resp.url: ext = os.path.splitext(resp.url)[1] if ext: filename += ext return filename
Example #21
Source File: file.py From platypush with MIT License | 6 votes |
def __init__(self, source, *args, **kwargs): super().__init__(source, *args, **kwargs) self.path = os.path.abspath(os.path.expanduser( self.source[len(self._matched_handler):])) self.filename = self.path.split('/')[-1] if not os.path.isfile(self.path): raise FileNotFoundError('{} is not a valid file'. format(self.path)) self.mime_type = get_mime_type(source) if self.mime_type[:5] not in ['video', 'audio', 'image']: raise AttributeError('{} is not a valid media file (detected format: {})'. format(source, self.mime_type)) self.extension = mimetypes.guess_extension(self.mime_type) if self.url: self.url += self.extension self.content_length = os.path.getsize(self.path)
Example #22
Source File: upload.py From bepasty-server with BSD 2-Clause "Simplified" License | 6 votes |
def filter_filename(cls, filename, storage_name, content_type, content_type_hint): """ Filter filename. Only allow some basic characters and shorten to 50 characters. """ # Make up filename if we don't have one if not filename: if not content_type: content_type = content_type_hint # note: stdlib mimetypes.guess_extension is total crap if content_type.startswith("text/"): ext = ".txt" else: ext = ".bin" filename = storage_name + ext return cls._filename_re.sub('', filename)[:MAX_FILENAME_LENGTH]
Example #23
Source File: __init__.py From kivystudio with MIT License | 5 votes |
def _generate_image_from_art(self, art, path): pix = pix_from_art(art) ext = mimetypes.guess_extension(pix.mime) if ext == 'jpe': ext = 'jpg' image = self._generate_image_from_data( path, ext, pix.data ) self._thumbs[path] = image return image
Example #24
Source File: Mastodon.py From Mastodon.py with MIT License | 5 votes |
def media_post(self, media_file, mime_type=None, description=None, focus=None): """ Post an image, video or audio file. `media_file` can either be image data or a file name. If image data is passed directly, the mime type has to be specified manually, otherwise, it is determined from the file name. `focus` should be a tuple of floats between -1 and 1, giving the x and y coordinates of the images focus point for cropping (with the origin being the images center). Throws a `MastodonIllegalArgumentError` if the mime type of the passed data or file can not be determined properly. Returns a `media dict`_. This contains the id that can be used in status_post to attach the media file to a toot. """ if mime_type is None and (isinstance(media_file, str) and os.path.isfile(media_file)): mime_type = guess_type(media_file) media_file = open(media_file, 'rb') elif isinstance(media_file, str) and os.path.isfile(media_file): media_file = open(media_file, 'rb') if mime_type is None: raise MastodonIllegalArgumentError('Could not determine mime type' ' or data passed directly ' 'without mime type.') random_suffix = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10)) file_name = "mastodonpyupload_" + str(time.time()) + "_" + str(random_suffix) + mimetypes.guess_extension( mime_type) if focus != None: focus = str(focus[0]) + "," + str(focus[1]) media_file_description = (file_name, media_file, mime_type) return self.__api_request('POST', '/api/v1/media', files={'file': media_file_description}, params={'description': description, 'focus': focus})
Example #25
Source File: tensorflow_bind.py From trains with Apache License 2.0 | 5 votes |
def _add_audio(self, tag, step, values, audio_data=None): # only report images every specific interval if step % self.image_report_freq != 0: return None if values: audio_str = values['encodedAudioString'] audio_data = base64.b64decode(audio_str) if audio_data is None: return # noinspection PyProtectedMember title, series = self.tag_splitter(tag, num_split_parts=3, default_title='Audio', logdir_header='title', auto_reduce_num_split=True, force_add_prefix=self._logger._get_tensorboard_series_prefix()) step = self._fix_step_counter(title, series, step) stream = BytesIO(audio_data) if values: file_extension = guess_extension(values['contentType']) or \ '.{}'.format(values['contentType'].split('/')[-1]) else: # assume wav as default file_extension = '.wav' self._logger.report_media( title=title, series=series, iteration=step, stream=stream, file_extension=file_extension, max_history=self.max_keep_images, )
Example #26
Source File: nndownload.py From nndownload with MIT License | 5 votes |
def find_extension(mimetype): """Determine the file extension from the mimetype.""" return MIMETYPES.get(mimetype) or mimetypes.guess_extension(mimetype, strict=True) ## Nama methods
Example #27
Source File: tasks.py From lexpredict-contraxsuite with GNU Affero General Public License v3.0 | 5 votes |
def get_file_extension(file_name: str, file_path: str) -> Tuple[str, str]: """ Get file extension and determine file type. Any `text/plain` file is considered to have extension `.txt`. :param file_name: file name + extension :param file_path: full file path :return: (extension, type_string,), type_string: 'CONTENT' or 'ARCHIVE' """ _fn, ext = os.path.splitext(file_name) if not ext: known_extensions = {'text/plain': 'txt'} mt = python_magic.from_file(file_path) ext = known_extensions.get(mt) or mimetypes.guess_extension(mt) ext = ext or '' file_content = 'ARCHIVE' if ArchiveFile.check_file_is_archive(file_path, ext) else 'CONTENT' return ext, file_content
Example #28
Source File: forms.py From sample-platform with ISC License | 5 votes |
def validate_file(form, field) -> None: """ Validate sample being uploaded. :param form: form data :type form: UploadForm :param field: field to validate :type field: form field :raises ValidationError: when extension is not allowed :raises ValidationError: when mimetype is not allowed :raises ValidationError: when extension not provided and not supported """ # File cannot end with a forbidden extension filename, file_extension = os.path.splitext(field.data.filename) if len(file_extension) > 0: forbidden_ext = ForbiddenExtension.query.filter(ForbiddenExtension.extension == file_extension[1:]).first() if forbidden_ext is not None: raise ValidationError('Extension not allowed') mimetype = magic.from_buffer(field.data.read(1024), mime=True) # File Pointer returns to beginning field.data.seek(0, 0) # Check for permitted mimetype forbidden_mime = ForbiddenMimeType.query.filter(ForbiddenMimeType.mimetype == mimetype).first() if forbidden_mime is not None: raise ValidationError('File MimeType not allowed') extension = mimetypes.guess_extension(mimetype) if extension is not None: forbidden_real = ForbiddenExtension.query.filter(ForbiddenExtension.extension == extension[1:]).first() if forbidden_real is not None: raise ValidationError('Extension not allowed')
Example #29
Source File: cover.py From sacad with Mozilla Public License 2.0 | 5 votes |
def guessImageFormatFromHttpResponse(response): """ Guess file format from HTTP response, return format or None. """ extensions = [] # try to guess extension from response content-type header try: content_type = response.headers["Content-Type"] except KeyError: pass else: ext = mimetypes.guess_extension(content_type, strict=False) if ext is not None: extensions.append(ext) # try to extract extension from URL urls = list(response.history) + [response.url] for url in map(str, urls): ext = os.path.splitext(urllib.parse.urlsplit(url).path)[-1] if (ext is not None) and (ext not in extensions): extensions.append(ext) # now guess from the extensions for ext in extensions: try: return SUPPORTED_IMG_FORMATS[ext[1:]] except KeyError: pass
Example #30
Source File: core.py From hangoutsbot with GNU Affero General Public License v3.0 | 5 votes |
def upload_image(self, image_uri, sync, username, userid, channel_name): token = self.apikey logger.info('downloading %s', image_uri) filename = os.path.basename(image_uri) request = urllib.request.Request(image_uri) request.add_header("Authorization", "Bearer %s" % token) image_response = urllib.request.urlopen(request) content_type = image_response.info().get_content_type() filename_extension = mimetypes.guess_extension(content_type).lower() # returns with "." physical_extension = "." + filename.rsplit(".", 1).pop().lower() if physical_extension == filename_extension: pass elif filename_extension == ".jpe" and physical_extension in [ ".jpg", ".jpeg", ".jpe", ".jif", ".jfif" ]: # account for mimetypes idiosyncrancy to return jpe for valid jpeg pass else: logger.warning("unable to determine extension: {} {}".format(filename_extension, physical_extension)) filename += filename_extension logger.info('uploading as %s', filename) image_id = yield from self.bot._client.upload_image(image_response, filename=filename) logger.info('sending HO message, image_id: %s', image_id) yield from sync._bridgeinstance._send_to_internal_chat( sync.hangoutid, "shared media from slack", { "sync": sync, "source_user": username, "source_uid": userid, "source_title": channel_name }, image_id=image_id )