示例#1
0
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()
示例#2
0
    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)
示例#3
0
	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()
示例#4
0
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)
示例#5
0
    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")
示例#6
0
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
示例#7
0
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)
示例#8
0
    def configure_mimetypes():
        """
        Register keepass mimetypes.

        """
        mimetypes.add_type("application/x-keepass-database-v1", ".kdb")
        mimetypes.add_type("application/x-keepass-database-v2", ".kdbx")
示例#9
0
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
示例#10
0
    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
示例#11
0
文件: base.py 项目: vbraun/sagenb
    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)
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
示例#13
0
文件: utils.py 项目: shuge/pilgrim
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
示例#14
0
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
示例#15
0
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
示例#16
0
    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()
示例#17
0
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')
示例#18
0
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)"}
示例#19
0
文件: core.py 项目: bonega/subliminal
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
示例#20
0
文件: app.py 项目: westurner/pgs
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()')
示例#21
0
def after_init_apps(sender):
    import mimetypes
    from uliweb import settings
    
    for k, v in settings.get('MIME_TYPES').items():
        if not k.startswith('.'):
            k = '.' + k
        mimetypes.add_type(v, k)
示例#22
0
def register_custom_mimetypes():
    """Registers additional extension/mimetype mappings.

    This is used for mimetypes/extensions that are not in the official
    mapping but useful, e.g. because indico has special handling for
    files with that type.
    """
    mimetypes.add_type(b'text/markdown', b'.md')
示例#23
0
 def update_config(self, config_):
     toolkit.add_template_directory(config_, 'templates')
     toolkit.add_public_directory(config_, 'public')
     toolkit.add_resource('fanstatic', 'wsdl_view')
     relpath = "./xslt/wsdl_to_html.xslt"
     path = os.path.join(os.path.dirname(os.path.realpath(__file__)), relpath)
     self.wsdl_to_html = etree.XSLT(etree.parse(path))
     mimetypes.add_type('wsdl', '.wsdl')
示例#24
0
    def _add_xslt_mimetype(self):
        """Register the mimetype for .xsl files in order for Django to serve static.

        .xsl files with the correct mimetype

        """
        # 'application/xslt+xml'
        mimetypes.add_type('text/xsl', '.xsl')
示例#25
0
def _get_mimetypes():
    from pywps.formats import FORMATS
    mimetypes.init()
    for pywps_format in FORMATS:
        (mtype, ext) = FORMATS[pywps_format]

        # NOTE: strict is set to True: mimetype will be added to system
        # mimetypes, zip -> application/zipped-shapefile
        mimetypes.add_type(mtype, ext, True)
示例#26
0
文件: web.py 项目: spl0k/supysonic
def create_application(config = None):
    global app

    # Flask!
    app = Flask(__name__)
    app.config.from_object('supysonic.config.DefaultConfig')

    if not config: # pragma: nocover
        config = IniConfig.from_common_locations()
    app.config.from_object(config)

    # Set loglevel
    logfile = app.config['WEBAPP']['log_file']
    if logfile: # pragma: nocover
        from logging.handlers import TimedRotatingFileHandler
        handler = TimedRotatingFileHandler(logfile, when = 'midnight')
        handler.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] %(message)s"))
        logger.addHandler(handler)
    loglevel = app.config['WEBAPP']['log_level']
    if loglevel:
        logger.setLevel(getattr(logging, loglevel.upper(), logging.NOTSET))

    # Initialize database
    init_database(app.config['BASE']['database_uri'])
    app.wsgi_app = db_session(app.wsgi_app)

    # Insert unknown mimetypes
    for k, v in app.config['MIMETYPES'].items():
        extension = '.' + k.lower()
        if extension not in mimetypes.types_map:
            mimetypes.add_type(v, extension, False)

    # Initialize Cache objects
    # Max size is MB in the config file but Cache expects bytes
    cache_dir = app.config['WEBAPP']['cache_dir']
    max_size_cache = app.config['WEBAPP']['cache_size'] * 1024**2
    max_size_transcodes = app.config['WEBAPP']['transcode_cache_size'] * 1024**2
    app.cache = Cache(path.join(cache_dir, "cache"), max_size_cache)
    app.transcode_cache = Cache(path.join(cache_dir, "transcodes"), max_size_transcodes)

    # Test for the cache directory
    cache_path = app.config['WEBAPP']['cache_dir']
    if not path.exists(cache_path):
        makedirs(cache_path) # pragma: nocover

    # Read or create secret key
    app.secret_key = get_secret_key('cookies_secret')

    # Import app sections
    if app.config['WEBAPP']['mount_webui']:
        from .frontend import frontend
        app.register_blueprint(frontend)
    if app.config['WEBAPP']['mount_api']:
        from .api import api
        app.register_blueprint(api, url_prefix = '/rest')

    return app
示例#27
0
文件: app.py 项目: joeyespo/grip
    def add_content_types(self):
        """
        Adds the application/x-font-woff and application/octet-stream
        content types if they are missing.

        Override to add additional content types on initialization.
        """
        mimetypes.add_type('application/x-font-woff', '.woff')
        mimetypes.add_type('application/octet-stream', '.ttf')
示例#28
0
def main():
    # Ajout des types de fichier que je sui sur de rencontrer
    mimetypes.add_type('video', '.mkv')

    try:
        opts, args = getopt.getopt(argv[1:], 's:d:vDp')
    except getopt.GetoptError, err:
        print str(err)
        exit(2)
示例#29
0
def guess_type(extenstion):
    global mimetype_initialised

    if not mimetype_initialised:
        mimetypes.init()
        mimetypes.add_type('application/xhtml+xml', '.xhtml')
        mimetype_initialised = True

    return mimetypes.guess_type(extenstion)
示例#30
0
    def test_mimetype_is_determined_by_using_python_mtr(self, browser):
        mimetypes.add_type("application/foobar", ".foo")

        browser.login().open(self.dossier.absolute_url())
        factoriesmenu.add("Document")

        browser.fill({"File": ("File data", "file.foo", "application/i-dont-know")}).save()
        assert_message("Item created")
        doc = browser.context.restrictedTraverse("document-1")
        self.assertEquals("application/foobar", doc.file.contentType)
示例#31
0
Django settings for mysite project.

Generated by 'django-admin startproject' using Django 3.1.2.

For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""

from pathlib import Path
import os
import mimetypes

mimetypes.add_type("image/jpg", ".jpg", True)
mimetypes.add_type("image/png", ".png", True)
mimetypes.add_type("application/javascript", ".js", True)
mimetypes.add_type("text/css", ".css", True)

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATES_DIR = os.path.join(BASE_DIR, 'templates')
STATIC_DIR = os.path.join(BASE_DIR, 'static')
MEDIA_DIR = os.path.join(BASE_DIR, "media")
SITE_CONFIG_DIR = os.path.join(BASE_DIR, "config")
LOCALE_DIR = os.path.join(BASE_DIR, "locale")
LOCALE_PATHS = (LOCALE_DIR, )

DATETIME_INPUT_FORMATS = [
    '%Y/%m/%d %H:%M',
示例#32
0
# Embedded file name: /usr/lib/enigma2/python/Components/Scanner.py
from Plugins.Plugin import PluginDescriptor
from Components.PluginComponent import plugins
import os
from mimetypes import guess_type, add_type
add_type('application/x-debian-package', '.ipk')
add_type('application/ogg', '.ogg')
add_type('audio/x-flac', '.flac')
add_type('application/x-dream-package', '.dmpkg')
add_type('application/x-dream-image', '.nfi')
add_type('video/MP2T', '.ts')
add_type('video/x-dvd-iso', '.iso')
add_type('video/x-matroska', '.mkv')
add_type('audio/x-matroska', '.mka')
add_type('video/mpeg', '.mts')


def getType(file):
    type, _ = guess_type(file)
    if type is None:
        if file[-12:].lower() == 'video_ts.ifo':
            return 'video/x-dvd'
        p = file.rfind('.')
        if p == -1:
            return
        ext = file[p + 1:].lower()
        if ext == 'dat' and file[-11:-6].lower() == 'avseq':
            return 'video/x-vcd'
    return type

示例#33
0
from datetime import datetime, timezone
from flask import current_app
import io
import mimetypes
from mongoframes import *
import numpy
from PIL import Image
import time

# Fix for missing mimetypes
mimetypes.add_type('text/csv', '.csv')
mimetypes.add_type('image/webp', '.webp')

from utils import get_file_length, generate_uid

__all__ = ['Asset', 'Variation']


class Variation(SubFrame):
    """
    A variation of an asset transformed by one or more operations.
    """

    _fields = {'name', 'version', 'ext', 'meta', 'store_key'}

    def __str__(self):
        return self.store_key

    @staticmethod
    def find_face(im, bias=None, padding=0, min_padding=0):
        """
示例#34
0
# print SQL queries in shell_plus
SHELL_PLUS_PRINT_SQL = False

# show colored logs in the dev environment
# to disable this, set `COLOR_LOGS = False` in awx/settings/local_settings.py
LOGGING['handlers']['console']['()'] = 'awx.main.utils.handlers.ColorHandler'
# task system does not propagate to AWX, so color log these too
LOGGING['handlers']['task_system'] = LOGGING['handlers']['console'].copy()
COLOR_LOGS = True

# Pipe management playbook output to console
LOGGING['loggers']['awx.isolated.manager.playbooks']['propagate'] = True

ALLOWED_HOSTS = ['*']

mimetypes.add_type("image/svg+xml", ".svg", True)
mimetypes.add_type("image/svg+xml", ".svgz", True)

# Disallow sending session cookies over insecure connections
SESSION_COOKIE_SECURE = False

# Disallow sending csrf cookies over insecure connections
CSRF_COOKIE_SECURE = False

# Override django.template.loaders.cached.Loader in defaults.py
template = next(
    (tpl_backend
     for tpl_backend in TEMPLATES if tpl_backend['NAME'] == 'default'),
    None)  # noqa
template['OPTIONS']['loaders'] = (
    'django.template.loaders.filesystem.Loader',
示例#35
0
    def handle_request(self, request, payload):
        print('Request path: {0}'.format(request.path))
        data = self.create_data(request, 200)
        if request.method == 'POST':
            post_data = yield from payload.read()
            post_data = MultiDict(parse_qsl(post_data.decode('utf-8')))
            print('POST data:')
            for key, val in post_data.items():
                print('\t- {0}: {1}'.format(key, val))
            data['post_data'] = dict(post_data)

        # Submit the event to the TANNER service
        event_result = yield from self.submit_data(data)

        # Log the event to slurp service if enabled
        if self.run_args.slurp_enabled:
            yield from self.submit_slurp(request.path)
        response = aiohttp.Response(
            self.writer, status=200, http_version=request.version
        )
        content_type = None
        mimetypes.add_type('text/html','.php')
        mimetypes.add_type('text/html', '.aspx')
        base_path = os.path.join('/opt/snare/pages', self.run_args.page_dir)
        if event_result is not None and ('payload' in event_result['response']['message']['detection'] and event_result['response']['message']['detection']['payload'] is not None):
            payload_content = event_result['response']['message']['detection']['payload']
            if type(payload_content) == dict:
                if payload_content['page'].startswith('/'):
                    payload_content['page'] = payload_content['page'][1:]
                page_path = os.path.join(base_path, payload_content['page'])
                content = '<html><body></body></html>'
                if os.path.exists(page_path):
                    content_type = mimetypes.guess_type(page_path)[0]
                    with open(page_path, encoding='utf-8') as p:
                        content = p.read()
                soup = BeautifulSoup(content, 'html.parser')
                script_tag = soup.new_tag('div')
                script_tag.append(BeautifulSoup(payload_content['value'], 'html.parser'))
                soup.body.append(script_tag)
                content = str(soup).encode()

            else:
                content_type = mimetypes.guess_type(payload_content)[0]
                content = payload_content.encode('utf-8')
        else:
            query = None
            if request.path == '/':
                parsed_url = self.run_args.index_page
            else:
                parsed_url = urlparse(unquote(request.path))
                if parsed_url.query:
                    query = '?' + parsed_url.query
                parsed_url = parsed_url.path
                if parsed_url.startswith('/'):
                    parsed_url = parsed_url[1:]
            path = os.path.normpath(os.path.join(base_path, parsed_url))
            if os.path.isfile(path) and path.startswith(base_path):
                content_type = mimetypes.guess_type(path)[0]
                with open(path, 'rb') as fh:
                    content = fh.read()
                if content_type:
                    if 'text/html' in content_type:
                        content = yield from self.handle_html_content(content)
            else:
                content_type = None
                content = None
                response = aiohttp.Response(
                    self.writer, status=404, http_version=request.version
                )
        response.add_header('Server', self.run_args.server_header)

        if 'cookies' in data and 'sess_uuid' in data['cookies']:
            previous_sess_uuid = data['cookies']['sess_uuid']
        else:
            previous_sess_uuid = None

        if event_result is not None and ('sess_uuid' in event_result['response']['message']):
            cur_sess_id = event_result['response']['message']['sess_uuid']
            if previous_sess_uuid is None or not previous_sess_uuid.strip() or previous_sess_uuid != cur_sess_id:
                response.add_header('Set-Cookie', 'sess_uuid=' + cur_sess_id)

        if not content_type:
            response.add_header('Content-Type', 'text/plain')
        else:
            response.add_header('Content-Type', content_type)
        if content:
            response.add_header('Content-Length', str(len(content)))
        response.send_headers()
        if content:
            response.write(content)
        yield from response.write_eof()
示例#36
0
def make_app(global_conf, full_stack=True, static_files=True, **app_conf):
    """Create a Pylons WSGI application and return it

    ``global_conf``
        The inherited configuration for this application. Normally from
        the [DEFAULT] section of the Paste ini file.

    ``full_stack``
        Whether or not this application provides a full WSGI stack (by
        default, meaning it handles its own exceptions and errors).
        Disable full_stack when this application is "managed" by another
        WSGI middleware.

    ``static_files``
        Whether this application serves its own static files; disable
        when another web server is responsible for serving them.

    ``app_conf``
        The application's local configuration. Normally specified in the
        [app:<name>] section of the Paste ini file (where <name>
        defaults to main).
    """
    # Configure the Pylons environment
    load_environment(global_conf, app_conf)

    # Add missing mime types
    for k, v in app_conf.iteritems():
        if k.startswith('mimetype.'):
            mimetypes.add_type(v, k[8:])

    # The Pylons WSGI app
    app = PylonsApp()

    # Routing/Session/Cache Middleware
    app = RoutesMiddleware(app, config['routes.map'])
    if asbool(config.get('etag.enable', True)):
        app = EtagMiddleware(app, config)
    if asbool(config.get('compact.enable', True)):
        app = CompactMiddleware(app, config)
    app = SessionMiddleware(app, config)
    app = CacheMiddleware(app, config)

    # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares)
    if asbool(full_stack):
        app = ErrorMiddleware(app, config)

    # Establish the Registry for this application
    app = RegistryManager(app)

    if asbool(static_files):
        # Serve static files
        max_age = asint(config.get('cache_max_age.staticmax', 1))
        static_external_paths = config['pylons.paths']['static_external_paths']
        static_development_paths = config['pylons.paths']['static_development_paths']
        static_release_paths = config['pylons.paths']['static_release_paths']
        static_viewer_paths = config['pylons.paths']['static_viewer_paths']

        # Order is important for performance
        # file paths will be check sequentially the first time the file is requested
        if asbool(config.get('scripts.development', False)):
            all_path_items = [(path, 0) for path in static_development_paths]
        else:
            all_path_items = [(path, 28800) for path in static_development_paths]
        all_path_items.extend([(path, max_age) for path in static_external_paths])
        all_path_items.extend([(path, max_age) for path in static_release_paths])

        if asbool(config.get('viewer.development', 'false')):
            # We only need to supply the jslib files with the viewer in development mode
            all_path_items.extend([(path, 0) for path in static_viewer_paths])
            all_path_items.extend([(os.path.join(path, 'jslib'), 0) for path in static_viewer_paths])

        app = StaticFilesMiddleware(app, all_path_items)
        app = StaticGameFilesMiddleware(app, staticmax_max_age=max_age)

    app = GzipMiddleware(app, config)
    app = MetricsMiddleware(app, config)
    app = LoggingMiddleware(app, config)

    __add_customisations()
    __init_controllers()

    # Last middleware is the first middleware that gets executed for a request, and last for a response
    return app
示例#37
0
"""
Module with enum constants and utm utils
"""

import itertools as it
import mimetypes
import utm

from pyproj import Proj
from enum import Enum

from .config import SHConfig
from ._version import __version__

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


class PackageProps:
    """ Class for obtaining package properties. Currently it supports obtaining package version."""
    @staticmethod
    def get_version():
        return __version__


class ServiceType(Enum):
    """ Enum constant class for type of service

    Supported types are WMS, WCS, WFS, AWS, IMAGE
    """
    WMS = 'wms'
    WCS = 'wcs'
示例#38
0
from homeassistant.components.http.view import HomeAssistantView
from homeassistant.config import async_hass_config_yaml
from homeassistant.const import CONF_NAME, EVENT_THEMES_UPDATED
from homeassistant.core import callback
from homeassistant.helpers import service
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.translation import async_get_translations
from homeassistant.loader import async_get_integration, bind_hass

from .storage import async_setup_frontend_storage

# mypy: allow-untyped-defs, no-check-untyped-defs

# Fix mimetypes for borked Windows machines
# https://github.com/home-assistant/home-assistant-polymer/issues/3336
mimetypes.add_type("text/css", ".css")
mimetypes.add_type("application/javascript", ".js")

DOMAIN = "frontend"
CONF_THEMES = "themes"
CONF_EXTRA_HTML_URL = "extra_html_url"
CONF_EXTRA_HTML_URL_ES5 = "extra_html_url_es5"
CONF_EXTRA_MODULE_URL = "extra_module_url"
CONF_EXTRA_JS_URL_ES5 = "extra_js_url_es5"
CONF_FRONTEND_REPO = "development_repo"
CONF_JS_VERSION = "javascript_version"
EVENT_PANELS_UPDATED = "panels_updated"

DEFAULT_THEME_COLOR = "#03A9F4"

MANIFEST_JSON = {
示例#39
0
    if mime_type == "image/gif" and file_path:
        img = Image.open(file_path)
        if img.is_animated:
            return "video"
        else:
            return "image"
    entry = SUPPORTED_MEDIATYPES.get(mime_type)
    if entry:
        return entry["gmt"]
    gmt = mime_type.split("/")[0]
    if gmt in list(GMT):
        logger.warning(f"Guessing GMT from {mime_type}")
        return gmt


mimetypes.add_type("text/markdown", ".md")
mimetypes.add_type("text/markdown", ".markdown")
mimetypes.add_type("application/x-mobipocket-ebook", ".mobi")
mimetypes.add_type("application/x-sqlite3", ".sqlite")
mimetypes.add_type("video/mp4", ".f4v")

SUPPORTED_MEDIATYPES = {
    # Text Formats
    "application/rtf": {
        "gmt": "text",
        "ext": "rtf"
    },
    "application/msword": {
        "gmt": "text",
        "ext": "doc"
    },
示例#40
0
def main(argv):

    flags = argparser.parse_args()
    # Process flags and read their values.
    path_to_folder_with_apks = flags.path_to_folder_with_apks
    recursive = flags.recursive
    package_name = flags.package_name
    obb_postfix = flags.obb_postfix
    track_name = flags.track
    service_account = flags.service_account
    key_file = flags.key_file

    mimetypes.add_type("application/octet-stream", ".obb")

    apk_obb_tuples_list = list()
    for path, _, files in os.walk(path_to_folder_with_apks):
        for name in files:
            if name.endswith('.apk'):
                apk_full_name = os.path.abspath(os.path.join(path, name))
                apk_base_name, _ = os.path.splitext(apk_full_name)
                obb_full_name = apk_base_name + '.' + obb_postfix
                if not os.path.exists(obb_full_name):
                    obb_full_name = ""
                apk_obb_tuples_list.append((apk_full_name, obb_full_name))
        if not recursive:
            break

    if len(apk_obb_tuples_list) == 0:
        print 'Can`t find any apk file, exit..'
        sys.exit(1)
    else:
        print 'List APKs for process:'
        for apk, obb in apk_obb_tuples_list:
            print '\tAPK: %s' % apk
            if obb:
                print '\t\tOBB: %s' % obb

    # Load the key in PKCS 12 format that you downloaded from the Google APIs
    # Console when you created your Service account.
    f = file(key_file, 'rb')
    key = f.read()
    f.close()

    # Create an httplib2.Http object to handle our HTTP requests and authorize it
    # with the Credentials. Note that the first parameter, service_account_name,
    # is the Email address created for the Service account. It must be the email
    # address associated with the key that was created.
    credentials = client.SignedJwtAssertionCredentials(
        service_account,
        key,
        scope='https://www.googleapis.com/auth/androidpublisher')
    http = httplib2.Http()
    http = credentials.authorize(http)

    service = build('androidpublisher', 'v2', http=http)

    try:
        edit_request = service.edits().insert(body={},
                                              packageName=package_name)
        result = edit_request.execute()
        edit_id = result['id']

        apks_versions = []

        for apk_file, obb_file in apk_obb_tuples_list:

            print 'Start uploading %s' % apk_file

            apk_response = service.edits().apks().upload(
                editId=edit_id, packageName=package_name,
                media_body=apk_file).execute()
            print 'APK with version code %d has been uploaded' % apk_response[
                'versionCode']
            apks_versions.append(apk_response['versionCode'])
            if obb_file:
                print 'Start uploading %s' % obb_file
                obb_response = service.edits().expansionfiles().upload(
                    apkVersionCode=apk_response['versionCode'],
                    expansionFileType='main',
                    editId=edit_id,
                    packageName=package_name,
                    media_body=obb_file).execute()

                print 'OBB %s has been uploaded' % obb_response['expansionFile']

        track_response = service.edits().tracks().update(
            editId=edit_id,
            track=track_name,
            packageName=package_name,
            body={
                u'versionCodes': apks_versions
            }).execute()

        print 'Track %s is set for version code(s) %s' % (
            track_response['track'], str(track_response['versionCodes']))

        commit_request = service.edits().commit(
            editId=edit_id, packageName=package_name).execute()

        print 'Edit "%s" has been committed' % (commit_request['id'])

    except client.AccessTokenRefreshError:
        print(
            'The credentials have been revoked or expired, please re-run the '
            'application to re-authorize')
示例#41
0
# This group of application settings get overridden for local execution
DATA_PATH = "/data"
HA_BASE_URL = "http://hassio/homeassistant/api"
HA_TOKEN = str(os.environ.get("HASSIO_TOKEN"))
HA_MQTT_PUBLISH_URL = HA_BASE_URL + "/services/mqtt/publish"

# This group of application settings are the same regardless of
# local or production execution.
HA_MQTT_RESULT_TOPIC = "googlebackup/result"
HA_MQTT_RESULT_RETAIN = "False"
HA_MQTT_ADHOC_RESULT_TOPIC = "googlebackup/adhocresult"
HA_MQTT_ADHOC_RESULT_RETAIN = "False"

# Initialize mimetypes
mimetypes.init()
mimetypes.add_type("text/x-yaml", ".yaml")
mimetypes.add_type("text/x-yaml", ".yml")

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "70mm#takprrt)6$=k(2h!dikc0d6qwo5#czl(+!oy$=xdv^2=l"

SESSION_COOKIE_SECURE = False
CSRF_COOKIE_SECURE = False

ALLOWED_HOSTS = ["*", "[::1]"]

# Application definition
示例#42
0
"""
Django settings for todoApp project.

Generated by 'django-admin startproject' using Django 3.0.4.

For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""

import os
import mimetypes
mimetypes.add_type("text/css", ".css", True)

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '8zag84xzcd-cjhgl+0gc83w0s5lf=9fp)wn$*ghflgp*6le+3k'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition
示例#43
0
from readthedocs.builds.constants import LATEST
from readthedocs.builds.models import Version
from readthedocs.builds.views import BuildTriggerMixin
from readthedocs.core.utils.extend import SettingsOverrideObject
from readthedocs.projects.models import Project
from readthedocs.projects.templatetags.projects_tags import sort_version_aware
from readthedocs.proxito.views.mixins import ServeDocsMixin
from readthedocs.proxito.views.utils import _get_project_data_from_request

from .base import ProjectOnboardMixin
from ..constants import PRIVATE


log = logging.getLogger(__name__)
search_log = logging.getLogger(__name__ + '.search')
mimetypes.add_type('application/epub+zip', '.epub')


class ProjectTagIndex(ListView):

    """List view of public :py:class:`Project` instances."""

    model = Project

    def get_queryset(self):
        queryset = Project.objects.public(self.request.user)
        queryset = queryset.exclude(users__profile__banned=True)

        self.tag = get_object_or_404(Tag, slug=self.kwargs.get('tag'))
        queryset = queryset.filter(tags__slug__in=[self.tag.slug])
示例#44
0
Generated by 'django-admin startproject' using Django 2.0.1.

For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""

import os
import sys
import fcntl
import shutil
import subprocess
import mimetypes
mimetypes.add_type("application/wasm", ".wasm", True)

from pathlib import Path

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = str(Path(__file__).parents[2])

ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS',
                               'localhost,127.0.0.1').split(',')
INTERNAL_IPS = ['127.0.0.1']

try:
    sys.path.append(BASE_DIR)
    from keys.secret_key import SECRET_KEY  # pylint: disable=unused-import
except ImportError:
示例#45
0
import sys
import os
import json
import subprocess
import click

import StringIO
import gzip
from datetime import datetime
from textwrap import dedent
import mimetypes

TARGETS = ['infra', 'dev', 'int', 'prod']

mimetypes.init()
mimetypes.add_type('application/x-font-ttf', '.ttf')
mimetypes.add_type('application/x-font-opentype', '.otf')
mimetypes.add_type('application/vnd.ms-fontobject', '.eot')
mimetypes.add_type('application/json', '.json')
mimetypes.add_type('text/cache-manifest', '.appcache')
mimetypes.add_type('text/plain', '.txt')

NO_COMPRESS = [
    'image/png', 'image/jpeg', 'image/x-icon', 'image/vnd.microsoft.icon',
    'application/x-font-ttf', 'application/x-font-opentype',
    'application/vnd.ms-fontobject'
]

project = os.environ.get('PROJECT', 'mf-geoadmin3')

示例#46
0
def mime(conf):
    '''Set up MIME types'''
    for ext, type in conf.items():
        mimetypes.add_type(type, ext, strict=True)
示例#47
0
import mimetypes
from database.Database import db
from flask import Flask, send_from_directory, render_template
from flask_cors import CORS, cross_origin
from routes import router, api_router

mimetypes.add_type("application/javascript", ".js", True)

# TODO: Carregar todos os modelos na inicialização

db_name = 'cv_service.db'  # Read from config
db.set_name(db_name)
db.create()

app = Flask(__name__, static_folder='../static', static_url_path="")

app.url_map.strict_slashes = False
app.config['CORS_HEADERS'] = 'Content-Type'
app.register_blueprint(api_router)

CORS(app)


@app.route('/model/<model>/<extension>', methods=['GET'])
def index_files(model, extension):
    folder = '../tf_models/client'
    return send_from_directory(folder, f'{model}/{extension}')


@app.route('/application', methods=['GET'])
def index_redirect():
示例#48
0
import gzip
import zlib
import traceback

from . import VERSION_STRING
from .logger import LOGGER
from .compat import (urljoin, urlsplit, quote, unquote, unquote_to_bytes,
                     urlopen, urllib_get_content_type, urllib_get_charset,
                     urllib_get_filename, Request, parse_email, pathname2url,
                     unicode, base64_decode, StreamingGzipFile,
                     FILESYSTEM_ENCODING)

# Unlinke HTML, CSS and PNG, the SVG MIME type is not always builtin
# in some Python version and therefore not reliable.
if sys.version_info[0] >= 3:
    mimetypes.add_type('image/svg+xml', '.svg')
else:
    # Native strings required.
    mimetypes.add_type(b'image/svg+xml', b'.svg')

# See http://stackoverflow.com/a/11687993/1162888
# Both are needed in Python 3 as the re module does not like to mix
# http://tools.ietf.org/html/rfc3986#section-3.1
UNICODE_SCHEME_RE = re.compile('^([a-zA-Z][a-zA-Z0-9.+-]+):')
BYTES_SCHEME_RE = re.compile(b'^([a-zA-Z][a-zA-Z0-9.+-]+):')


def iri_to_uri(url):
    """Turn an IRI that can contain any Unicode character into an ASCII-only
    URI that conforms to RFC 3986.
    """
示例#49
0
from __future__ import absolute_import

from mimetypes import add_type, guess_type

add_type("text/gcode", ".gcode")
add_type("application/fcode", ".fc")
add_type("binary/flux-firmware", ".fxfw")


def validate_ext(filename, match_mimetype):
    real_mimetype, _ = guess_type(filename)
    return real_mimetype == match_mimetype
示例#50
0
import mimetypes
import os.path

from openpyxl.descriptors.serialisable import Serialisable
from openpyxl.descriptors import String, Sequence
from openpyxl.xml.functions import fromstring
from openpyxl.xml.constants import (
    ARC_CORE, ARC_CONTENT_TYPES, ARC_WORKBOOK, ARC_APP, ARC_THEME, ARC_STYLE,
    ARC_SHARED_STRINGS, EXTERNAL_LINK, THEME_TYPE, STYLES_TYPE, XLSX, XLSM,
    XLTM, XLTX, WORKSHEET_TYPE, COMMENTS_TYPE, SHARED_STRINGS, DRAWING_TYPE,
    CHART_TYPE, CHARTSHAPE_TYPE, CHARTSHEET_TYPE, CONTYPES_NS)
from openpyxl.xml.functions import tostring

# initialise mime-types
mimetypes.init()
mimetypes.add_type('application/xml', ".xml")
mimetypes.add_type('application/vnd.openxmlformats-package.relationships+xml',
                   ".rels")
mimetypes.add_type("application/vnd.ms-office.vbaProject", ".bin")
mimetypes.add_type("application/vnd.openxmlformats-officedocument.vmlDrawing",
                   ".vml")
mimetypes.add_type("image/x-emf", ".emf")


class FileExtension(Serialisable):

    tagname = "Default"

    Extension = String()
    ContentType = String()
示例#51
0
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""

# Build paths inside the project like this: os.path.join(DIRNAME, ...)
import os
SETTINGS_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.join(SETTINGS_DIR, '..')

# Fix for weird x-png MIME types:
import mimetypes
mimetypes.add_type('image/png', '.png', True)

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
'''///////////////////////////////////////////////////////////////////
..// Obviously remember to change the SECRET_KEY for each new app! //
.///////////////////////////////////////////////////////////////////'''

# SECURITY WARNING: keep the secret key used in production secret!
# Make this unique, and don't share it with anybody.
SECRET_KEY = ('\xa6\x49\x1a\x53\x1d\x0e\x07\x12\x1e\x30'
              '\x06\x7b\x92\x57\xd5\x32\xef\x1a\xf7\x9e'
              '\x76\xe4\x94\x27\xf6\x56\x07\x51\x3c\xe6'
              '\xd3\x8c\x0a\x20\xdb\x27\xcc\x05\x32\x60'
              '\x37\xd5\x84\xb6\x18\x86\x07\x7b\x49\xa0')
'''///////////////////////////////////////////////////////////////////
示例#52
0
    '',
    '.md',
    '.rst'
]
README_MIMETYPES = {
    '.md': 'text/markdown',
    '.rst': 'text/x-rst',
}
README_MAX_SIZE = 512 * 1024  # 512 KiB

ReadmeFile = collections.namedtuple(
    'ReadmeFile', ['text', 'mimetype', 'hash']
)

for _ext, _type in README_MIMETYPES.items():
    mimetypes.add_type(_type, _ext)


class FileSizeError(Exception):
    pass


def find_readme(directory):
    for ext in README_EXTENSIONS:
        filename = os.path.join(directory, README_NAME + ext)
        if os.path.exists(filename):
            return filename
    return None


def get_readme(directory, root_dir=None, filename=None):
示例#53
0
            sys.exit('Hash-algorithm %s not one of: %s' %
                     (c.hash_algo, halgos))

    log.info("+++Pypiserver started with: %s", c)

    return c, packages


def auth_by_htpasswd_file(htPsswdFile, username, password):
    """The default ``config.auther``."""
    if htPsswdFile is not None:
        htPsswdFile.load_if_changed()
        return htPsswdFile.check_password(username, password)


mimetypes.add_type("application/octet-stream", ".egg")
mimetypes.add_type("application/octet-stream", ".whl")
mimetypes.add_type("text/plain", ".asc")

#### Next 2 functions adapted from :mod:`distribute.pkg_resources`.
#
component_re = re.compile(r'(\d+ | [a-z]+ | \.| -)', re.I | re.VERBOSE)
replace = {
    'pre': 'c',
    'preview': 'c',
    '-': 'final-',
    'rc': 'c',
    'dev': '@'
}.get

示例#54
0
import re
import sys
import base64
import mimetypes

from grit import lazy_re
from grit import util
from grit.format import minifier

# There is a python bug that makes mimetypes crash if the Windows
# registry contains non-Latin keys ( http://bugs.python.org/issue9291
# ). Initing manually and blocking external mime-type databases will
# prevent that bug and if we add svg manually, it will still give us
# the data we need.
mimetypes.init([])
mimetypes.add_type('image/svg+xml', '.svg')

# webm video type is not always available if mimetype package is outdated.
mimetypes.add_type('video/webm', '.webm')

DIST_DEFAULT = 'chromium'
DIST_ENV_VAR = 'CHROMIUM_BUILD'
DIST_SUBSTR = '%DISTRIBUTION%'

# Matches beginning of an "if" block.
_BEGIN_IF_BLOCK = lazy_re.compile(
    r'<if [^>]*?expr=("(?P<expr1>[^">]*)"|\'(?P<expr2>[^\'>]*)\')[^>]*?>')

# Matches ending of an "if" block.
_END_IF_BLOCK = lazy_re.compile(r'</if>')
示例#55
0
    def __init__(self, sample):
        self.sample = sample

        if not mimetypes.inited:
            mimetypes.init()
            mimetypes.add_type('application/javascript', '.jse')
示例#56
0
from Plugins.Plugin import PluginDescriptor
from Components.PluginComponent import plugins

import os
from mimetypes import guess_type, add_type

add_type("application/x-debian-package", ".ipk")
add_type("application/ogg", ".ogg")
add_type("audio/x-flac", ".flac")
add_type("application/x-dream-package", ".dmpkg")
add_type("application/x-dream-image", ".nfi")
add_type("video/MP2T", ".ts")
add_type("video/x-dvd-iso", ".iso")
add_type("video/x-matroska", ".mkv")
add_type("audio/x-matroska", ".mka")
add_type("video/mpeg", ".mts")

def getType(file):
	(type, _) = guess_type(file)
	if type is None:
		# Detect some unknown types
		if file[-12:].lower() == "video_ts.ifo":
			return "video/x-dvd"
		if file == "/media/audiocd/cdplaylist.cdpls":
			return "audio/x-cda"

		p = file.rfind('.')
		if p == -1:
			return None
		ext = file[p+1:].lower()
示例#57
0
        'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
    'parkManagement/templates/parkSrc/',
]

if DEBUG:
    import mimetypes
    mimetypes.add_type("application/font-woff", ".woff", True)
示例#58
0
文件: base.py 项目: mwasilew/jobserv
 def __init__(self):
     mimetypes.add_type('text/plain', '.log')
 def RunOnce(self):
     """Run this once on init."""
     mimetypes.add_type("application/font-woff", ".woff", True)
示例#60
0
def configureServer(test=False, plugins=None, curConfig=None):
    """
    Function to setup the cherrypy server. It configures it, but does
    not actually start it.

    :param test: Set to True when running in the tests.
    :type test: bool
    :param plugins: If you wish to start the server with a custom set of
        plugins, pass this as a list of plugins to load. Otherwise,
        will use the PLUGINS_ENABLED setting value from the db.
    :param curConfig: The configuration dictionary to update.
    """
    if curConfig is None:
        curConfig = config.getConfig()

    appconf = {
        '/': {
            'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
            'request.show_tracebacks': test,
            'request.methods_with_bodies': ('POST', 'PUT', 'PATCH'),
            'response.headers.server': 'Girder %s' % __version__,
            'error_page.default': _errorDefault
        }
    }
    # Add MIME types for serving Fontello files from staticdir;
    # these may be missing or incorrect in the OS
    mimetypes.add_type('application/vnd.ms-fontobject', '.eot')
    mimetypes.add_type('application/x-font-ttf', '.ttf')
    mimetypes.add_type('application/font-woff', '.woff')

    curConfig.update(appconf)

    if test:
        # Force some config params in testing mode
        curConfig.update({
            'server': {
                'mode': 'testing',
                'api_root': 'api/v1',
                'static_root': 'static',
                'api_static_root': '../static',
                'cherrypy_server': True
            }
        })

    mode = curConfig['server']['mode'].lower()
    logprint.info('Running in mode: ' + mode)
    cherrypy.config['engine.autoreload.on'] = mode == 'development'

    _setupCache()

    # Don't import this until after the configs have been read; some module
    # initialization code requires the configuration to be set up.
    from girder.api import api_main

    root = webroot.Webroot()
    api_main.addApiToNode(root)

    girder.events.setupDaemon()
    cherrypy.engine.subscribe('start', girder.events.daemon.start)
    cherrypy.engine.subscribe('stop', girder.events.daemon.stop)

    if plugins is None:
        plugins = getPlugins()

    routeTable = loadRouteTable()
    info = {
        'config': appconf,
        'serverRoot': root,
        'serverRootPath': routeTable[constants.GIRDER_ROUTE_ID],
        'apiRoot': root.api.v1,
        'staticRoot': routeTable[constants.GIRDER_STATIC_ROUTE_ID]
    }

    plugin._loadPlugins(plugins, info)
    root, appconf = info['serverRoot'], info['config']

    return root, appconf