当前位置: 首页>>代码示例>>Python>>正文


Python mimetypes.add_type函数代码示例

本文整理汇总了Python中mimetypes.add_type函数的典型用法代码示例。如果您正苦于以下问题:Python add_type函数的具体用法?Python add_type怎么用?Python add_type使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了add_type函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: main

def main():
    """Start the cherrypy server."""
    mimetypes.add_type('text/x-ada', '.ads')
    mimetypes.add_type('text/x-ada', '.adb')
    cherrypy.log.screen = False
    cherrypy.server.socket_port = 8080
    cherrypy.server.socket_host = socket.gethostbyaddr(socket.gethostname())[0]
    cherrypy.tree.mount(
        HTTPEmailViewer(sys.argv[1]), "/", {'/': {}})
    cherrypy.engine.start()
    try:
        open_cmd = 'xdg-open' if sys.platform.startswith('linux') else 'open'
        try:
            subprocess.check_call(
                [open_cmd,
                 'http://%s:%d' % (
                    cherrypy.server.socket_host,
                    cherrypy.server.socket_port)],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE)
        except subprocess.CalledProcessError:
            print('open http://%s:%d to see the email in your browser' % (
                cherrypy.server.socket_host,
                cherrypy.server.socket_port))
        sys.stdin.read(1)
        print('stopping the server, please wait...')
    finally:
        cherrypy.engine.exit()
        cherrypy.server.stop()
开发者ID:enzbang,项目名称:open-email-in-browser,代码行数:29,代码来源:main.py

示例2: configure

def configure(ctx, py, yaml, skip_backend_validation=False):
    """
    Given the two different config files, set up the environment.

    NOTE: Will only execute once, so it's safe to call multiple times.
    """
    global __installed
    if __installed:
        return

    # Make sure that our warnings are always displayed
    import warnings
    warnings.filterwarnings('default', '', Warning, r'^sentry')

    # Add in additional mimetypes that are useful for our static files
    # which aren't common in default system registries
    import mimetypes
    for type, ext in (
        ('application/json', 'map'),
        ('application/font-woff', 'woff'),
        ('application/font-woff2', 'woff2'),
        ('application/vnd.ms-fontobject', 'eot'),
        ('application/x-font-ttf', 'ttf'),
        ('application/x-font-ttf', 'ttc'),
        ('font/opentype', 'otf'),
    ):
        mimetypes.add_type(type, '.' + ext)

    from .importer import install

    if yaml is None:
        # `yaml` will be None when SENTRY_CONF is pointed
        # directly to a file, in which case, this file must exist
        if not os.path.exists(py):
            if ctx:
                raise click.ClickException("Configuration file does not exist. Use 'sentry init' to initialize the file.")
            raise ValueError("Configuration file does not exist at '%s'" % click.format_filename(py))
    elif not os.path.exists(yaml) and not os.path.exists(py):
        if ctx:
            raise click.ClickException("Configuration file does not exist. Use 'sentry init' to initialize the file.")
        raise ValueError("Configuration file does not exist at '%s'" % click.format_filename(yaml))

    os.environ['DJANGO_SETTINGS_MODULE'] = 'sentry_config'

    install('sentry_config', py, DEFAULT_SETTINGS_MODULE)

    # HACK: we need to force access of django.conf.settings to
    # ensure we don't hit any import-driven recursive behavior
    from django.conf import settings
    hasattr(settings, 'INSTALLED_APPS')

    from .initializer import initialize_app, on_configure
    initialize_app({
        'config_path': py,
        'settings': settings,
        'options': yaml,
    }, skip_backend_validation=skip_backend_validation)
    on_configure({'settings': settings})

    __installed = True
开发者ID:atlantech,项目名称:sentry,代码行数:60,代码来源:settings.py

示例3: upload

	def upload(self, obj, source_name):
		mimetypes.add_type('video/x-flv', 'flv', False)
		
		# Save the state of this media as uploading
		obj.post.state = POST_UPLOADING
		obj.post.save()
		obj.state = u'Uploading'
		obj.save()
		
		# Get the MIME type
		mime, encoding = mimetypes.guess_type(source_name)
		
		f = open(source_name)
		try:
			# Save the file in a format Django can upload to S3
			obj.post.media.create(
				mimetype = mime,
				content = File(
					f,
					name = '%s%s' % (
						os.path.splitext(source_name)[0],
						os.path.splitext(source_name)[-1]
					)
				)
			)
			
			return True
		finally:
			f.close()
开发者ID:iamsteadman,项目名称:meegloo,代码行数:29,代码来源:__init__.py

示例4: recursive_search

def recursive_search(entry):
    """searches files in the dir"""
    files = []
    if os.path.isdir(entry):
        # TODO if hidden folder, don't keep going (how to handle windows/mac/linux ?)
        for e in os.listdir(entry):
            files += recursive_search(os.path.join(entry, e))
    elif os.path.isfile(entry):
        # Add mkv mimetype to the list
        mimetypes.add_type("video/x-matroska", ".mkv")
        mimetype = mimetypes.guess_type(entry)[0]
        if mimetype in SUPPORTED_FORMATS:
            # Add it to the list only if there is not already one (or forced)
            basepath = os.path.splitext(entry)[0]
            if not (os.path.exists(basepath + ".srt") or os.path.exists(basepath + ".sub")):
                files.append(os.path.normpath(entry))
            else:
                logger.info(
                    "Skipping file %s as it already has a subtitle. Use the --force option to force the download"
                    % entry
                )
        else:
            logger.info(
                "%s mimetype is '%s' which is not a supported video format (%s)" % (entry, mimetype, SUPPORTED_FORMATS)
            )
    return files
开发者ID:gry,项目名称:downganizer,代码行数:26,代码来源:subtitledownloader.py

示例5: configure_mimetypes

def configure_mimetypes():
    global CONFIGURED_MIMETYPES
    if not CONFIGURED_MIMETYPES:
        for (type_, ext) in ADDL_MIMETYPES:
            mimetypes.add_type(type_, ext)
    CONFIGURED_MIMETYPES = True
    log.debug('configure_mimetypes()')
开发者ID:westurner,项目名称:pgs,代码行数:7,代码来源:app.py

示例6: __init__

    def __init__(self, **kwargs):
        self.param_container = kwargs.get("cloudfiles_container")
        self.param_user = kwargs.get("cloudfiles_user")
        self.param_api_key = kwargs.get("cloudfiles_api_key")
        self.param_host = kwargs.get("cloudfiles_host")
        self.param_use_servicenet = kwargs.get("cloudfiles_use_servicenet")

        # the Mime Type webm doesn't exists, let's add it
        mimetypes.add_type("video/webm", "webm")

        if not self.param_host:
            _log.info("No CloudFiles host URL specified, " "defaulting to Rackspace US")

        self.connection = cloudfiles.get_connection(
            username=self.param_user,
            api_key=self.param_api_key,
            servicenet=True if self.param_use_servicenet == "true" or self.param_use_servicenet == True else False,
        )

        _log.debug("Connected to {0} (auth: {1})".format(self.connection.connection.host, self.connection.auth.host))

        if not self.param_container == self.connection.get_container(self.param_container):
            self.container = self.connection.create_container(self.param_container)
            self.container.make_public(ttl=60 * 60 * 2)
        else:
            self.container = self.connection.get_container(self.param_container)

        _log.debug("Container: {0}".format(self.container.name))

        self.container_uri = self.container.public_ssl_uri()
开发者ID:pythonsnake,项目名称:MediaDwarf,代码行数:30,代码来源:cloudfiles.py

示例7: scan

def scan(entry, depth=0, max_depth=3):
    """Scan a path and return a list of tuples (filepath, set(languages), has single)"""
    if depth > max_depth and max_depth != 0:  # we do not want to search the whole file system except if max_depth = 0
        return []
    if depth == 0:
        entry = os.path.abspath(entry)
    if os.path.isfile(entry):  # a file? scan it
        if depth != 0:  # trust the user: only check for valid format if recursing
            mimetypes.add_type("video/x-matroska", ".mkv")
            if mimetypes.guess_type(entry)[0] not in FORMATS:
                return []
        # check for .lg.ext and .ext
        available_languages = set()
        has_single = False
        basepath = os.path.splitext(entry)[0]
        for l in LANGUAGES:
            for e in EXTENSIONS:
                if os.path.exists(basepath + ".%s.%s" % (l, e)):
                    available_languages.add(l)
                if os.path.exists(basepath + ".%s" % e):
                    has_single = True
        return [(os.path.normpath(entry), available_languages, has_single)]
    if os.path.isdir(entry):  # a dir? recurse
        result = []
        for e in os.listdir(entry):
            result.extend(scan(os.path.join(entry, e), depth + 1))
        return result
    return []  # anything else
开发者ID:bonega,项目名称:subliminal,代码行数:28,代码来源:core.py

示例8: isTextKind

def isTextKind(remotename, trace=True):
    add_type('text/x-python-win', '.pyw')
    mimetype, encoding = guess_type(remotename, strict=False)
    mimetype = mimetype or '?/?'
    maintype = mimetype.split('/')[0]
    if trace: print(maintype, encoding or '')
    return maintype == 'text' and encoding == None
开发者ID:andrej2704,项目名称:network,代码行数:7,代码来源:downloaddlat_modular.py

示例9: _configure_mimetypes

def _configure_mimetypes():
    # Fix mimetypes on misconfigured systems
    mimetypes.add_type('text/css', '.css')
    mimetypes.add_type('application/sfont', '.otf')
    mimetypes.add_type('application/sfont', '.ttf')
    mimetypes.add_type('application/javascript', '.js')
    mimetypes.add_type('application/font-woff', '.woff')
开发者ID:pymedusa,项目名称:SickRage,代码行数:7,代码来源:__init__.py

示例10: getDecoder

def getDecoder(filename):
    # https://msdn.microsoft.com/en-us/library/windows/desktop/dn424129(v=vs.85).aspx
    mimetypes.add_type("image/vnd-ms.dds", ".dds")
    """
    NOTICE: This is not a standard, see also
    https://github.com/jleclanche/mpqt/blob/master/packages/blizzard.xml
    """
    mimetypes.add_type("image/vnd.bliz.blp", ".blp")

    filename = filename.lower()
    mime_type, encoding = mimetypes.guess_type(filename)

    if mime_type == "image/vnd-ms.dds":
        return codecs.DDS

    if mime_type == "image/png":
        return codecs.PNG

    if mime_type == "image/vnd.microsoft.icon":
        return codecs.ICO

    # if filename.endswith(".blp"):
    #     return codecs.BLP
    if mime_type == "image/vnd.bliz.blp":
        return codecs.BLP

    if filename.endswith(".ftc") or filename.endswith(".ftu"):
        return codecs.FTEX
开发者ID:shuge,项目名称:pilgrim,代码行数:28,代码来源:utils.py

示例11: __init__

    def __init__(self, *args, **kwds):
        self.startup_token = kwds.pop("startup_token", None)
        Flask.__init__(self, *args, **kwds)

        self.config["SESSION_COOKIE_HTTPONLY"] = False

        self.root_path = SAGENB_ROOT

        self.add_static_path("/css", os.path.join(DATA, "sage", "css"))
        self.add_static_path("/images", os.path.join(DATA, "sage", "images"))
        self.add_static_path("/javascript", DATA)
        self.add_static_path("/static", DATA)
        self.add_static_path("/java", DATA)
        self.add_static_path("/java/jmol", os.path.join(os.environ["SAGE_ROOT"], "local", "share", "jmol"))
        import mimetypes

        mimetypes.add_type("text/plain", ".jmol")

        #######
        # Doc #
        #######
        # These "should" be in doc.py
        DOC = os.path.join(SAGE_DOC, "output", "html", "en")
        self.add_static_path("/pdf", os.path.join(SAGE_DOC, "output", "pdf"))
        self.add_static_path("/doc/static", DOC)
开发者ID:vbraun,项目名称:sagenb,代码行数:25,代码来源:base.py

示例12: isTextKind

def isTextKind(remotename, trace=True):
    add_type("text/x-python-win", ".pyw")
    mimetype, encoding = guess_type(remotename, strict=False)
    maintype = mimetype.split("/")[0]
    if trace:
        print(maintype, encoding or "")
    return maintype == "text" and encoding == None
开发者ID:death-finger,项目名称:Scripts,代码行数:7,代码来源:downloadflat_modular.py

示例13: update_config

    def update_config(self, config):
        toolkit.add_template_directory(config, 'templates')
        toolkit.add_public_directory(config, 'public')
        toolkit.add_resource('fanstatic', 'dane_publiczne')
        toolkit.add_resource('fanstatic', 'ckanext-reclineview')

        mimetypes.add_type('application/json', '.geojson')

        # TODO ckan-dev load all properties from SystemInfo at load, instead of using app_globals.auto_update:
        # TODO ckan-dev def get_globals_key(key):   should allow ckanext.
        app_globals.auto_update += [
            'ckanext.danepubliczne.maintenance_flash',
        ]
        for locale in h.get_available_locales():
            lang = locale.language
            app_globals.auto_update += ['ckan.site_intro_text-' + lang, 'ckan.site_about-' + lang]


        # don't show user names in activity stream
        def get_snippet_actor_org(activity, detail):
            return literal('''<span class="actor">%s</span>'''
            % (linked_org_for(activity['user_id'], 0, 30))
            )

        activity_streams.activity_snippet_functions['actor'] = get_snippet_actor_org
开发者ID:Emp0ri0,项目名称:ckanext-danepubliczne,代码行数:25,代码来源:plugin.py

示例14: configure_mimetypes

    def configure_mimetypes():
        """
        Register keepass mimetypes.

        """
        mimetypes.add_type("application/x-keepass-database-v1", ".kdb")
        mimetypes.add_type("application/x-keepass-database-v2", ".kdbx")
开发者ID:bh,项目名称:python-keepass-httpd,代码行数:7,代码来源:core.py

示例15: __init__

    def __init__(self, *args, **kwds):
        self.startup_token = kwds.pop('startup_token', None)
        Flask.__init__(self, *args, **kwds)
        self.session_interface = OldSecureCookieSessionInterface()

        self.config['SESSION_COOKIE_HTTPONLY'] = False

        self.root_path = SAGENB_ROOT

        self.add_static_path('/css', os.path.join(DATA, "sage", "css"))
        self.add_static_path('/images', os.path.join(DATA, "sage", "images"))
        self.add_static_path('/javascript', DATA)
        self.add_static_path('/static', DATA)
        self.add_static_path('/java', DATA)
        self.add_static_path('/java/jmol', os.path.join(os.environ["SAGE_ROOT"],"local","share","jmol"))
        import mimetypes
        mimetypes.add_type('text/plain','.jmol')


        #######
        # Doc #
        #######
        #These "should" be in doc.py
        DOC = os.path.join(SAGE_DOC, 'output', 'html', 'en')
        self.add_static_path('/pdf', os.path.join(SAGE_DOC, 'output', 'pdf'))
        self.add_static_path('/doc/static', DOC)
开发者ID:SnarkBoojum,项目名称:sagenb,代码行数:26,代码来源:base.py


注:本文中的mimetypes.add_type函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。