Given an app, return that app wrapped in iWSGIMiddleware
164407
def make_middleware(app=None, *args, **kw):
    
    app = iWSGIMiddleware(app, *args, **kw)
    return app
1031401
def get(self, path):
        """"""

        path = path.strip('/')
        self.log.info('Appmode get: %s', path)

        # Abort if the app path is not below configured trusted_path.
        if not path.startswith(self.trusted_path):
            self.log.warn('Appmode refused to launch %s outside trusted path %s.', path, self.trusted_path)
            raise web.HTTPError(401, 'Notebook is not within trusted Appmode path.')

        cm = self.contents_manager

        # will raise 404 on not found
        try:
            model = cm.get(path, content=False)
        except web.HTTPError as e:
            if e.status_code == 404 and 'files' in path.split('/'):
                # 404, but '/files/' in URL, let FilesRedirect take care of it
                return FilesRedirectHandler.redirect_to_files(self, path)
            else:
                raise
        if model['type'] != 'notebook':
            # not a notebook, redirect to files
            return FilesRedirectHandler.redirect_to_files(self, path)

        # fix back button navigation
        self.add_header("Cache-Control", "cache-control: private, max-age=0, no-cache, no-store")

        # gather template parameters
        tmp_path = self.mk_tmp_copy(path)
        tmp_name = tmp_path.rsplit('/', 1)[-1]
        render_kwargs = {
            'notebook_path': tmp_path,
            'notebook_name': tmp_name,
            'kill_kernel': False,
            'mathjax_url': self.mathjax_url,
            'mathjax_config': self.mathjax_config,
            'show_edit_button': self.show_edit_button,
            'show_other_buttons': self.show_other_buttons,
        }

        # template parameters changed over time
        if hasattr(orig_handler, "get_custom_frontend_exporters"):
            get_cfw = orig_handler.get_custom_frontend_exporters
            render_kwargs['get_custom_frontend_exporters'] = get_cfw

        # Ok let's roll ....
        self.write(self.render_template('appmode.html', **render_kwargs))
989214
function asyncify(app) {
    for (let name of methodNames) {
        let method = app[name];
        if (typeof method === 'function') {
            let func;
            if (name === 'route') {
                func = function() {
                    const router = method.apply(app, arguments);
                    return asyncify(router);
                };
            } else {
                func = function() {
                    const args = Array.prototype.slice.call(arguments);
                    const newArgs = args.map(value => {
                        if (typeof value === 'function') {
                            value = wrapView(value);
                        }
                        return value;
                    });
                    return method.apply(app, newArgs);
                };
            }
            app[name] = func;
        }
    }
    return app;
}
438468
def add(app, url = None, path = None, endpoint=None, decorate=None, index='index.html', **options):
    """"""

    url = url or app.static_url_path or ''
    path = os.path.abspath(path or app.static_folder or '.')
    endpoint = endpoint or 'static_' + os.path.basename(path)
    decorate = decorate or (lambda f: f)
    endpoints = {}

    if path == app.static_folder:
        raise ValueError('Files in `{}` path are already automatically served on `{}` URL by Flask.'
            ' Set Flask app static_folder to None, if you want to serve them using Flask Ecstatic at `{}` URL'
            .format(path, app.static_url_path, url))

    @app.route(url + '/<path:filename>', endpoint = endpoint)
    @handle404
    @decorate
    def static_files(filename):
        if index:
            filename = safe_join(path, filename)
            if os.path.isdir(filename):
                filename = os.path.join(filename, index)
            return send_file(filename, **options)
        else:
            return send_from_directory(path, filename, **options)

    endpoints[endpoint] = static_files

    if index:
         @app.route(url + '/', endpoint = endpoint + '_index')
         @handle404
         @decorate
         def static_index():
             return send_from_directory(path, index, **options)

         endpoints[endpoint + '_index'] = static_index

         if url:
             @app.route(url, endpoint = endpoint + '_index_bare')
             @handle404
             @decorate
             def static_index_bare():
                 return send_from_directory(path, index, **options)

             endpoints[endpoint + '_index_bare'] = static_index_bare

    return endpoints
1022351
def wsgi_wrap(app):
    '''
    
    '''
    @wraps(app)
    def wrapped(environ, start_response):
        status_headers = [None, None]
        def _start_response(status, headers):
            status_headers[:] = [status, headers]
        body = app(environ, _start_response)
        ret = body, status_headers[0], status_headers[1]
        return ret
    return wrapped
187340
def register_app(self, name: str, app: Callable = None) -> Callable:
        
        if app is None:
            def dec(app):
                """ inner decorator for register app """
                assert app is not None
                self.register_app(name, app)
                return app
            return dec
        self.applications[name] = app
        return None
1358120
def debug_application(self, environ, start_response):
        """"""
        app_iter = None
        try:
            app_iter = self.app(environ, start_response)
            for item in app_iter:
                yield item
            if hasattr(app_iter, 'close'):
                app_iter.close()
        except Exception:
            if hasattr(app_iter, 'close'):
                app_iter.close()

            context = RequestContext({'environ':dict(environ)})
            for injector in self.context_injectors:
                context.update(injector(environ))

            traceback = get_current_traceback(skip=1, show_hidden_frames=self.show_hidden_frames,
                                              context=context)
            for frame in traceback.frames:
                self.frames[frame.id] = frame
            self.tracebacks[traceback.id] = traceback

            try:
                start_response('500 INTERNAL SERVER ERROR', [
                    ('Content-Type', 'text/html; charset=utf-8'),
                    # Disable Chrome's XSS protection, the debug
                    # output can cause false-positives.
                    ('X-XSS-Protection', '0'),
                    ])
            except Exception:
                # if we end up here there has been output but an error
                # occurred.  in that situation we can do nothing fancy any
                # more, better log something into the error log and fall
                # back gracefully.
                environ['wsgi.errors'].write(
                    'Debugging middleware caught exception in streamed '
                    'response at a point where response headers were already '
                    'sent.\n')
            else:
                yield traceback.render_full(
                    evalex=self.evalex,
                    secret=self.secret
                ).encode('utf-8', 'replace')

            # This will lead to double logging in case backlash logger is set to DEBUG
            # but this is actually wanted as some environments, like WebTest, swallow
            # wsgi.environ making the traceback totally disappear.
            log.debug(traceback.plaintext)
            traceback.log(environ['wsgi.errors'])
989967
def build_finished(app, exception):
    
    # Skip for non-html or if javascript is not inlined
    if not app.env.config.wavedrom_html_jsinline:
        return

    if app.config.offline_skin_js_path is not None:
        copy_static_entry(path.join(app.builder.srcdir, app.config.offline_skin_js_path), path.join(app.builder.outdir, '_static'), app.builder)
    if app.config.offline_wavedrom_js_path is not None:
        copy_static_entry(path.join(app.builder.srcdir, app.config.offline_wavedrom_js_path), path.join(app.builder.outdir, '_static'), app.builder)
948483
function (appIdOrSlug, params) {
    var path = this.constructPath(constants.APPS, appIdOrSlug);
    return this.Core.GET(path, params);
  }
6338
def pyoidcMiddleware(func):
    

    def wrapper(environ, start_response):
        data = get_or_post(environ)
        cookies = environ.get("HTTP_COOKIE", "")
        resp = func(request=data, cookie=cookies)
        return resp(environ, start_response)

    return wrapper
633622
def require_app(app_name, api_style=False):
    
    iterable = (inspect.getmodule(frame[0]) for frame in inspect.stack())
    modules = [module for module in iterable if module is not None]
    if api_style:
        m = modules[2]  # skip a frame for "api" module
    else:
        m = modules[1]
    m._REQUIRED_APP = getattr(m, '_REQUIRED_APP', [])
    m._REQUIRED_APP.append(app_name)
    LOG.debug('require_app: %s is required by %s', app_name, m.__name__)
1048770
def _get_wrapper():
		
		if not pmxbot.config.get('use_ssl', False):
			return lambda x: x
		return importlib.import_module('ssl').wrap_socket
1116043
def app_1(env, start_response):
    """"""

    from uwsgiconf.runtime.environ import uwsgi_env

    start_response('200 OK', [('Content-Type','text/html')])

    data = [
        '<h1>uwsgiconf demo: one file</h1>',

        '<div>uWSGI version: %s</div>' % uwsgi_env.get_version(),
        '<div>uWSGI request ID: %s</div>' % uwsgi_env.request.id,
    ]

    return encode(data)
958766
def _get_webapp(self):
        
        settings = {
            "PORT"          : self._port,
            #"static_path"   : app_path(__conf__.STATIC_DIR_NAME),
            #"template_path" : app_path(__conf__.TEMPLATE_DIR_NAME),
            "debug"         : __conf__.DEBUG,
            "cookie_secret" : __conf__.COOKIE_SECRET
        }

        self.settings.update(settings)
        return WebApplication(self._handlers, **settings)
430976
def get_current_app(self):
        """"""
        self.request(EP_GET_CURRENT_APP_INFO)
        return None if self.last_response is None else self.last_response.get('payload').get('appId')
1113879
def get_renderer(app, id):
    
    renderer = app.extensions.get('nav_renderers', {})[id]

    if isinstance(renderer, tuple):
        mod_name, cls_name = renderer
        mod = import_module(mod_name)

        cls = mod
        for name in cls_name.split('.'):
            cls = getattr(cls, name)

        return cls

    return renderer
1341159
function getUiPart(modulePath, options) {
        var rootDir = this.injector.rootDir;
        var tplDir = (options && options.tplDir) || 'dist' + delim + 'tpls';
        var pathParts = modulePath.split(delim);
        var appName = pathParts[1];
        var len = modulePath.length;
        var filePath, fullModulePath, uipart, viewObj;

        // filePath has .js, modulePath does not
        if (modulePath.substring(len - 3) === '.js') {
            filePath = rootDir + delim + modulePath;
            fullModulePath = rootDir + delim + modulePath.substring(0, len - 3);
        }
        else {
            filePath = rootDir + delim + modulePath + '.js';
            fullModulePath = rootDir + delim + modulePath;
        }

        // if exists, get it
        if (fs.existsSync(filePath)) {
            uipart = this.injector.require(fullModulePath);
        }
        // else if in an app folder, try the common folder
        else if (appName !== 'common') {
            fullModulePath = fullModulePath.replace(delim + appName + delim, delim + 'common' + delim);
            uipart = this.injector.require(fullModulePath);
            appName = 'common';
        }

        // if no view, check to see if precompiled in tpl dir
        var viewFile = fullModulePath.replace(
            delim + 'app' + delim + appName + delim,
            delim + tplDir + delim + appName + delim
        );
        if (!uipart.view && fs.existsSync(viewFile + '.js')) {
            viewObj = this.injector.require(viewFile);
            uipart.view = function () {
                return viewObj;
            };
        }

        return uipart;
    }