我们从Python开源项目中,提取了以下47个代码示例,用于说明如何使用mimetypes.init()。
def test_non_latin_extension(self): import _winreg class MockWinreg(object): def __getattr__(self, name): if name == 'EnumKey': return lambda key, i: _winreg.EnumKey(key, i) + "\xa3" elif name == 'OpenKey': return lambda key, name: _winreg.OpenKey(key, name.rstrip("\xa3")) elif name == 'QueryValueEx': return lambda subkey, label: (u'?????/???????' , _winreg.REG_SZ) return getattr(_winreg, name) mimetypes._winreg = MockWinreg() try: # this used to throw an exception if registry contained non-Latin # characters in extensions (issue #9291) mimetypes.init() finally: mimetypes._winreg = _winreg
def test_non_latin_type(self): import _winreg class MockWinreg(object): def __getattr__(self, name): if name == 'QueryValueEx': return lambda subkey, label: (u'?????/???????', _winreg.REG_SZ) return getattr(_winreg, name) mimetypes._winreg = MockWinreg() try: # this used to throw an exception if registry contained non-Latin # characters in content types (issue #9291) mimetypes.init() finally: mimetypes._winreg = _winreg
def test_registry_read_error(self): import _winreg class MockWinreg(object): def OpenKey(self, key, name): if key != _winreg.HKEY_CLASSES_ROOT: raise WindowsError(5, "Access is denied") return _winreg.OpenKey(key, name) def __getattr__(self, name): return getattr(_winreg, name) mimetypes._winreg = MockWinreg() try: mimetypes.init() finally: mimetypes._winreg = _winreg
def __init__(self, route_table: Dict[str, Tuple[str, Any]], config: Dict[str, str], renderer, *args: Any) -> None: """ Create a new request handler. :param route_table: A dict with route information, the key is the route as string and the value is a tuple containing the http verb and the action to be executed when the route is requested. """ self._route_table = route_table self._resolver = RouteResolver(route_table) self._config = config self._renderer = renderer self._static_regex = re.compile('[/\w\-\.\_]+(?P<ext>\.\w{,4})$', re.IGNORECASE | re.DOTALL) BaseHTTPRequestHandler.__init__(self, *args) mimetypes.init()
def _build_image_extensions_list(): image_file_types = ["Photoshop Image", "Rendered Image", "Texture Image"] image_extensions = set() for image_file_type in image_file_types: image_extensions.update(COMMON_FILE_INFO[image_file_type]["extensions"]) # get all the image mime type image extensions as well mimetypes.init() types_map = mimetypes.types_map for (ext, mimetype) in types_map.iteritems(): if mimetype.startswith("image/"): image_extensions.add(ext.lstrip(".")) return list(image_extensions)
def __init__(self, queue, mutex): super().__init__(queue, mutex) self.itchat = itchat.new_instance() itchat.set_logging(loggingLevel=logging.getLogger().level, showOnCmd=False) self.itchat_msg_register() with mutex: self.itchat.auto_login(enableCmdQR=2, hotReload=True, statusStorageDir="storage/%s.pkl" % self.channel_id, exitCallback=self.exit_callback, qrCallback=self.console_qr_code) mimetypes.init(files=["mimetypes"]) self.logger.info("EWS Inited!!!\n---") # # Utilities #
def read_config(): global settings global extensions_map exist = os.path.isfile(setting_file_name) if not exist: print 'Creating config file...' shutil.copyfile(default_setting_file_name, setting_file_name) print 'Edit config.json and launch the script again.' sys.exit() with open(setting_file_name) as data_file: settings = json.load(data_file) #################################################################### #Load default mimetypes and update them with config.json extensions# #################################################################### if not mimetypes.inited: mimetypes.init() # try to read system mime.types extensions_map = mimetypes.types_map.copy() extensions_map.update({ '': 'application/octet-stream' # Default }) extensions_map.update(settings['extensions']) # Read extensions from config.json ##################################################################### return
def static_resources(config): from pkg_resources import resource_filename import mimetypes mimetypes.init() mimetypes.init([resource_filename('snowflakes', 'static/mime.types')]) config.add_static_view('static', 'static', cache_max_age=STATIC_MAX_AGE) config.add_static_view('profiles', 'schemas', cache_max_age=STATIC_MAX_AGE) favicon_path = '/static/img/favicon.ico' if config.route_prefix: favicon_path = '/%s%s' % (config.route_prefix, favicon_path) config.add_route('favicon.ico', 'favicon.ico') def favicon(request): subreq = request.copy() subreq.path_info = favicon_path response = request.invoke_subrequest(subreq) return response config.add_view(favicon, route_name='favicon.ico')
def get_content_type_by_filename(file_name): mime_type = "" mime_map = {} mime_map["js"] = "application/javascript" mime_map["xlsx"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" mime_map["xltx"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.template" mime_map["potx"] = "application/vnd.openxmlformats-officedocument.presentationml.template" mime_map["ppsx"] = "application/vnd.openxmlformats-officedocument.presentationml.slideshow" mime_map["pptx"] = "application/vnd.openxmlformats-officedocument.presentationml.presentation" mime_map["sldx"] = "application/vnd.openxmlformats-officedocument.presentationml.slide" mime_map["docx"] = "application/vnd.openxmlformats-officedocument.wordprocessingml.document" mime_map["dotx"] = "application/vnd.openxmlformats-officedocument.wordprocessingml.template" mime_map["xlam"] = "application/vnd.ms-excel.addin.macroEnabled.12" mime_map["xlsb"] = "application/vnd.ms-excel.sheet.binary.macroEnabled.12" mime_map["apk"] = "application/vnd.android.package-archive" try: suffix = "" name = os.path.basename(file_name) suffix = name.split('.')[-1] if suffix in mime_map.keys(): mime_type = mime_map[suffix] else: import mimetypes mimetypes.init() mime_type = mimetypes.types_map["." + suffix] except Exception: mime_type = 'application/octet-stream' if not mime_type: mime_type = 'application/octet-stream' return mime_type
def __init__(self, config_file=None, mimetype_files=None): super(Service, self).__init__(config_file) self.name = self.__class__.__name__ self.working_dir = boto.config.get('Pyami', 'working_dir') self.sd = ServiceDef(config_file) self.retry_count = self.sd.getint('retry_count', 5) self.loop_delay = self.sd.getint('loop_delay', 30) self.processing_time = self.sd.getint('processing_time', 60) self.input_queue = self.sd.get_obj('input_queue') self.output_queue = self.sd.get_obj('output_queue') self.output_domain = self.sd.get_obj('output_domain') if mimetype_files: mimetypes.init(mimetype_files)
def guess_mime_type_from_filename(file_path): """ Guess the type of a file based on its filename or URL. """ if not mimetypes.inited: mimetypes.init() mimetypes.add_type('application/javascript', '.jse') mt = mimetypes.guess_type(file_path)[0] if mt: return mt
def setUp(self): # ensure all entries actually come from the Windows registry self.original_types_map = mimetypes.types_map.copy() mimetypes.types_map.clear() mimetypes.init() self.db = mimetypes.MimeTypes()
def test_registry_parsing(self): # the original, minimum contents of the MIME database in the # Windows registry is undocumented AFAIK. # Use file types that should *always* exist: eq = self.assertEqual mimetypes.init() db = mimetypes.MimeTypes() eq(db.guess_type("foo.txt"), ("text/plain", None)) eq(db.guess_type("image.jpg"), ("image/jpeg", None)) eq(db.guess_type("image.png"), ("image/png", None))
def test_type_map_values(self): import _winreg class MockWinreg(object): def __getattr__(self, name): if name == 'QueryValueEx': return lambda subkey, label: (u'text/plain', _winreg.REG_SZ) return getattr(_winreg, name) mimetypes._winreg = MockWinreg() try: mimetypes.init() self.assertTrue(isinstance(mimetypes.types_map.values()[0], str)) finally: mimetypes._winreg = _winreg
def run(self): mimetypes.init() self.reload() try: from livereload import Server except ImportError: print("Please install the python3 livereload module to use this function.", file=sys.stderr) return server = Server(self.application) server.watch(self.content_root, self.reload) server.watch(self.theme_root, self.reload) server.serve(port=8000, host="localhost")
def guess_content_type_by_file_name(file_name): """ Get file type by filename. :type file_name: string :param file_name: None ======================= :return: **Type Value** """ mime_map = dict() mime_map["js"] = "application/javascript" mime_map["xlsx"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" mime_map["xltx"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.template" mime_map["potx"] = "application/vnd.openxmlformats-officedocument.presentationml.template" mime_map["ppsx"] = "application/vnd.openxmlformats-officedocument.presentationml.slideshow" mime_map["pptx"] = "application/vnd.openxmlformats-officedocument.presentationml.presentation" mime_map["sldx"] = "application/vnd.openxmlformats-officedocument.presentationml.slide" mime_map["docx"] = "application/vnd.openxmlformats-officedocument.wordprocessingml.document" mime_map["dotx"] = "application/vnd.openxmlformats-officedocument.wordprocessingml.template" mime_map["xlam"] = "application/vnd.ms-excel.addin.macroEnabled.12" mime_map["xlsb"] = "application/vnd.ms-excel.sheet.binary.macroEnabled.12" try: name = os.path.basename(file_name) suffix = name.split('.')[-1] if suffix in mime_map.keys(): mime_type = mime_map[suffix] else: import mimetypes mimetypes.init() mime_type = mimetypes.types_map["." + suffix] except: mime_type = 'application/octet-stream' if not mime_type: mime_type = 'application/octet-stream' return mime_type
def get_mimetype(file_path): mimetypes.init() return mimetypes.guess_type(file_path)[0]
def __init__(self, config_file=None, mimetype_files=None): ScriptBase.__init__(self, config_file) self.name = self.__class__.__name__ self.working_dir = boto.config.get('Pyami', 'working_dir') self.sd = ServiceDef(config_file) self.retry_count = self.sd.getint('retry_count', 5) self.loop_delay = self.sd.getint('loop_delay', 30) self.processing_time = self.sd.getint('processing_time', 60) self.input_queue = self.sd.get_obj('input_queue') self.output_queue = self.sd.get_obj('output_queue') self.output_domain = self.sd.get_obj('output_domain') if mimetype_files: mimetypes.init(mimetype_files)
def get_image_format(extension): mimetypes.init() return mimetypes.types_map[extension.lower()]
def load_config(pathname=None, server=None): """Load the ViewVC configuration file. SERVER is the server object that will be using this configuration. Consult the environment for the variable VIEWVC_CONF_PATHNAME and VIEWCVS_CONF_PATHNAME (its legacy name) and, if set, use its value as the path of the configuration file; otherwise, use PATHNAME (if provided). Failing all else, use a hardcoded default configuration path.""" debug.t_start('load-config') # See if the environment contains overrides to the configuration # path. If we have a SERVER object, consult its environment; use # the OS environment otherwise. env_get = server and server.getenv or os.environ.get env_pathname = (env_get("VIEWVC_CONF_PATHNAME") or env_get("VIEWCVS_CONF_PATHNAME")) # Try to find the configuration pathname by searching these ordered # locations: the environment, the passed-in PATHNAME, the hard-coded # default. pathname = (env_pathname or pathname or os.path.join(os.path.dirname(os.path.dirname(__file__)), "viewvc.conf")) # Load the configuration! cfg = config.Config() cfg.set_defaults() cfg.load_config(pathname, env_get("HTTP_HOST")) # Load mime types file(s), but reverse the order -- our # configuration uses a most-to-least preferred approach, but the # 'mimetypes' package wants things the other way around. if cfg.general.mime_types_files: files = cfg.general.mime_types_files[:] files.reverse() files = map(lambda x, y=pathname: os.path.join(os.path.dirname(y), x), files) mimetypes.init(files) debug.t_end('load-config') return cfg
def _fakeInit(self, paths): """ A mock L{mimetypes.init} that records the value of the passed C{paths} argument. @param paths: The paths that will be recorded. """ self.paths = paths
def test_defaultArgumentIsNone(self): """ By default, L{None} is passed to C{mimetypes.init}. """ static.loadMimeTypes(init=self._fakeInit) self.assertIdentical(self.paths, None)
def test_extraLocationsWork(self): """ Passed MIME type files are passed to C{mimetypes.init}. """ paths = ["x", "y", "z"] static.loadMimeTypes(paths, init=self._fakeInit) self.assertIdentical(self.paths, paths)
def test_usesGlobalInitFunction(self): """ By default, C{mimetypes.init} is called. """ # Checking mimetypes.inited doesn't always work, because # something, somewhere, calls mimetypes.init. Yay global # mutable state :) if _PY3: signature = inspect.signature(static.loadMimeTypes) self.assertIs(signature.parameters["init"].default, mimetypes.init) else: args, _, _, defaults = inspect.getargspec(static.loadMimeTypes) defaultInit = defaults[args.index("init")] self.assertIs(defaultInit, mimetypes.init)
def loadMimeTypes(mimetype_locations=None, init=mimetypes.init): """ Produces a mapping of extensions (with leading dot) to MIME types. It does this by calling the C{init} function of the L{mimetypes} module. This will have the side effect of modifying the global MIME types cache in that module. Multiple file locations containing mime-types can be passed as a list. The files will be sourced in that order, overriding mime-types from the files sourced beforehand, but only if a new entry explicitly overrides the current entry. @param mimetype_locations: Optional. List of paths to C{mime.types} style files that should be used. @type mimetype_locations: iterable of paths or L{None} @param init: The init function to call. Defaults to the global C{init} function of the C{mimetypes} module. For internal use (testing) only. @type init: callable """ init(mimetype_locations) mimetypes.types_map.update( { '.conf': 'text/plain', '.diff': 'text/plain', '.flac': 'audio/x-flac', '.java': 'text/plain', '.oz': 'text/x-oz', '.swf': 'application/x-shockwave-flash', '.wml': 'text/vnd.wap.wml', '.xul': 'application/vnd.mozilla.xul+xml', '.patch': 'text/plain' } ) return mimetypes.types_map
def __init__(self, queue, mutex, slaves): """ Initialization. Args: queue (queue.Queue): global message queue slaves (dict): Dictionary of slaves """ super().__init__(queue, mutex) self.slaves = slaves try: self.bot = telegram.ext.Updater(getattr(config, self.channel_id)['token']) except (AttributeError, KeyError): raise ValueError("Token is not properly defined. Please define it in `config.py`.") mimetypes.init(files=["mimetypes"]) self.admins = getattr(config, self.channel_id)['admins'] self.logger = logging.getLogger("plugins.%s.TelegramChannel" % self.channel_id) self.me = self.bot.bot.get_me() self.bot.dispatcher.add_handler(WhitelistHandler(self.admins)) self.bot.dispatcher.add_handler(telegram.ext.CommandHandler("link", self.link_chat_show_list, pass_args=True)) self.bot.dispatcher.add_handler(telegram.ext.CommandHandler("chat", self.start_chat_list, pass_args=True)) self.bot.dispatcher.add_handler(telegram.ext.CommandHandler("recog", self.recognize_speech, pass_args=True)) self.bot.dispatcher.add_handler(telegram.ext.CallbackQueryHandler(self.callback_query_dispatcher)) self.bot.dispatcher.add_handler(telegram.ext.CommandHandler("start", self.start, pass_args=True)) self.bot.dispatcher.add_handler(telegram.ext.CommandHandler("extra", self.extra_help)) self.bot.dispatcher.add_handler(telegram.ext.CommandHandler("help", self.help)) self.bot.dispatcher.add_handler(telegram.ext.CommandHandler("unlink_all", self.unlink_all)) self.bot.dispatcher.add_handler(telegram.ext.CommandHandler("info", self.info)) self.bot.dispatcher.add_handler( telegram.ext.RegexHandler(r"^/(?P<id>[0-9]+)_(?P<command>[a-z0-9_-]+)", self.extra_call, pass_groupdict=True)) self.bot.dispatcher.add_handler(telegram.ext.MessageHandler( telegram.ext.Filters.text | telegram.ext.Filters.photo | telegram.ext.Filters.sticker | telegram.ext.Filters.document | telegram.ext.Filters.venue | telegram.ext.Filters.location | telegram.ext.Filters.audio | telegram.ext.Filters.voice | telegram.ext.Filters.video, self.msg )) self.bot.dispatcher.add_error_handler(self.error) self.MUTE_CHAT_ID = self.MUTE_CHAT_ID.format(chat_id=self.channel_id) # Truncate string by bytes # Written by Mark Tolonen # http://stackoverflow.com/a/13738452/1989455
def __init__(self, url, working_dir='./.module_installer', root_dir=None): '''Initialize ModuleInstaller. Url should contain a fragment (#) with :param url: URL of file to install query parameters: http(s)://url/file.tar.gz#module_name=modname&module_path=Some/Path&move_to=/ module_name = local name of the module save_as = force download to save as name module_path = relative path, once the module has been extracted, to the module dir to "install" (copy the folder/file to the move_to path) move_to = path to extract the module to, relative to install_root ''' mimetypes.init() self.url = url parsed_url = urlparse.urlparse(url) qs = urlparse.parse_qs(parsed_url.fragment) #Make sure required query params exist if not qs.get('module_name') \ or not qs.get('module_path') \ or not qs.get('move_to'): raise ModuleDownloadException('ModuleInstaller: Missing query string parameters') self.module_path = qs['module_path'][0] self.move_to = qs['move_to'][0] self.mime_type = mimetypes.guess_type(parsed_url.path) self.working_dir = os.path.abspath(working_dir) self.module_name = qs['module_name'][0] ext = os.path.splitext(parsed_url.path) ext = os.path.splitext(ext[0])[1] + ext[1] #In case it's a .tar.gz save_as = qs.get('save_as') self.download_name = save_as[0] if save_as else self.module_name + ext #Try to get the mime type from save_as name, if one doesn't exist if not self.mime_type[0]: self.mime_type = mimetypes.guess_type(self.download_name) self.install_root = root_dir if root_dir else os.getcwd() #Absolute path where the modules will be installed self.full_install_path = os.path.join(self.install_root, self.move_to)