本文整理汇总了Python中mimetypes.add_type函数的典型用法代码示例。如果您正苦于以下问题:Python add_type函数的具体用法?Python add_type怎么用?Python add_type使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了add_type函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
示例16: guess_type
def guess_type(path, default=None):
for type, ext in settings.PIPELINE_MIMETYPES:
mimetypes.add_type(type, ext)
mimetype, _ = mimetypes.guess_type(path)
if not mimetype:
return default
return mimetype
开发者ID:ZibMedia,项目名称:django-pipeline,代码行数:7,代码来源:utils.py
示例17: guess_type
def guess_type(path, default=None):
for type, ext in settings.MIMETYPES:
mimetypes.add_type(type, ext)
mimetype, _ = mimetypes.guess_type(path)
if not mimetype:
return default
return smart_text(mimetype)
开发者ID:ChristopherBrix,项目名称:django-pipeline,代码行数:7,代码来源:utils.py
示例18: sort
def sort(dir, tmp_dir = path.abspath('/home/ndhuang/Pictures/'), all = False):
mimetypes.init()
mimetypes.add_type('image/x-nikon-nef', '.NEF')
sort_dir = path.join(tmp_dir, 'sorting')
img_files = os.listdir(dir)
i = 0
while i < len(img_files):
img = img_files[i]
if '.pp3' in img:
img_files.remove(img)
continue
elif not all and not re.match('DSC_(\d){4}\.', img):
img_files.remove(img)
continue
mt = mimetypes.guess_type(img)[0]
mt = mt.split('/')
if mt[0] != 'image':
raise RuntimeError('%s is not an image!' %img)
else:
i += 1
os.mkdir(sort_dir)
imgs = [[] for i in img_files]
for i in range(len(img_files)):
try:
imgs[i] = Img(path.join(dir, img_files[i]))
except KeyError:
print '%s is missing EXIF data!' %img_files[i]
# remove empty arrays
while [] in imgs:
imgs.remove([])
imgs = sorted(imgs)
pic_num = 1
copies = 1
for i, img in enumerate(imgs):
ext = img.path[-3:]
if i != 0 and imgs[i] == imgs[i - 1]:
dst = path.join(sort_dir,
'DSC_%04d-%d.%s' %(pic_num - 1, copies, ext))
copies += 1
else:
dst = path.join(sort_dir, 'DSC_%04d.%s' %(pic_num, ext))
pic_num += 1
copies = 1
os.rename(img.path, dst)
try:
os.rename(img.path + '.out.pp3', dst + '.out.pp3')
except OSError as err:
pass
try:
os.rename(img.path + '.pp3', dst + '.pp3')
except OSError as err:
pass
for f in os.listdir(dir):
os.rename(path.join(dir, f), path.join(sort_dir, f))
os.rmdir(dir)
os.rename(sort_dir, dir)
开发者ID:ndhuang,项目名称:python-lib,代码行数:60,代码来源:sortpics.py
示例19: _fill_attachment_form
def _fill_attachment_form(
self,
description,
file_object,
mark_for_review=False,
mark_for_commit_queue=False,
mark_for_landing=False,
is_patch=False,
filename=None,
mimetype=None,
):
self.browser["description"] = description
if is_patch:
self.browser["ispatch"] = ("1",)
# FIXME: Should this use self._find_select_element_for_flag?
self.browser["flag_type-1"] = ("?",) if mark_for_review else ("X",)
self.browser["flag_type-3"] = (self._commit_queue_flag(mark_for_landing, mark_for_commit_queue),)
filename = filename or "%s.patch" % timestamp()
if not mimetype:
mimetypes.add_type("text/plain", ".patch") # Make sure mimetypes knows about .patch
mimetype, _ = mimetypes.guess_type(filename)
if not mimetype:
mimetype = "text/plain" # Bugzilla might auto-guess for us and we might not need this?
self.browser.add_file(file_object, mimetype, filename, "data")
开发者ID:sohocoke,项目名称:webkit,代码行数:25,代码来源:bugzilla.py
示例20: graph_update_view
def graph_update_view(request):
import mimetypes
mimetypes.init()
mimetypes.add_type("pde","text/processing")
db = current_spectra.current_spectra(mode = 'r')
spectrum, timestamp, mode = db.getCurrentSpectrum()
spectime = time.localtime(timestamp)
spectrum = spectrum[cnf.modes[mode]['low_chan']:cnf.modes[mode]['high_chan'] + 1]
timeS = '%02i:%02i:%02i on %02i/%02i/%04i'%(spectime[3], spectime[4], spectime[5], spectime[2], spectime[1], spectime[0])
print mode
print cnf.modes[mode]['low_chan']
print cnf.getFreqs(mode)[cnf.modes[mode]['low_chan']]
print cnf.modes[mode]['high_chan'] + 1
print cnf.getFreqs(mode)[cnf.modes[mode]['high_chan'] + 1]
freqs = cnf.getFreqs(mode)[cnf.modes[mode]['low_chan']:cnf.modes[mode]['high_chan'] + 1] / 10e5
db.close()
miny = np.asscalar(spectrum.min())
maxy = np.asscalar(spectrum.max())
js = json.dumps(spectrum.tolist())
return {'spectrum':js,\
'freqs':json.dumps(freqs.tolist()),\
'maxx':freqs.max(),\
'minx':freqs.min(),\
'maxy':maxy,\
'miny':miny,\
'heading':"Spectrum taken at %s"%timeS,\
'xaxis':"Frequency (Mhz)",\
'yaxis':"Power (dBm)"}
开发者ID:MESAProductSolutions,项目名称:rta3web,代码行数:30,代码来源:views.py
注:本文中的mimetypes.add_type函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论