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
python类init()的实例源码
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 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 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 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 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 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 __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 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 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 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