Utility function for raising a werkzeug.exceptions.NotFound execption with the supplied WSGI environment
        and message.

        :param dict environ: The WSGI environment dictionary for the request
        :param str msg: The error message
604
def raise_not_found(self, environ, msg):
        
        raise NotFound(response=self.rewriterapp._error_response(environ, msg))
1316824
def exception(  # type: ignore
        self, msg, *args, exc_info=True, **kwargs
    ) -> Task:
        
        return self.error(msg, *args, exc_info=exc_info, **kwargs)
937828
def handler(self, environ, start_response):
        """"""
        logger = logging.getLogger(__name__ + '.WSGIProxyApplication.handler')
        url = urlparse(reconstruct_url(environ, self.port))

        # Create connection object
        try:
            connection = self.connection_class(url.netloc)
            # Build path
            path = url.geturl().replace('%s://%s' % (url.scheme, url.netloc),
                                        '')
        except Exception:
            start_response('501 Gateway Error', [('Content-Type', 'text/html')])
            logger.exception('Could not Connect')
            yield '<H1>Could not connect</H1>'
            return

        # Read in request body if it exists
        body = length = None
        try:
            length = int(environ['CONTENT_LENGTH'])
        except (KeyError, ValueError):

            # This is a situation where client HTTP POST is missing content-length.
            # This is also situation where (WebOb?) may screw up encoding and isert extranous = in the body.
            # https://github.com/ipython/ipython/issues/8416
            if environ["REQUEST_METHOD"] == "POST":
                if environ.get("CONTENT_TYPE") == 'application/x-www-form-urlencoded; charset=UTF-8':
                    body = environ['wsgi.input'].read()
                    try:
                        body = unquote_plus(body.decode("utf-8"))

                        # Fix extra = at end of JSON payload
                        if body.startswith("{") and body.endswith("}="):
                            body = body[0:len(body) - 1]

                    except Exception as e:
                        logger.exception(e)
                        logger.error("Could not decode body: %s", body)

                    length = len(body)
        else:
            body = environ['wsgi.input'].read(length)

        # Build headers
        logger.debug('environ = %r', environ)
        headers = dict(
            (key, value)
            for key, value in (
                # This is a hacky way of getting the header names right
                (key[5:].lower().replace('_', '-'), value)
                for key, value in environ.items()
                # Keys that start with HTTP_ are all headers
                if key.startswith('HTTP_')
            )
            if not is_hop_by_hop(key)
        )

        # Handler headers that aren't HTTP_ in environ
        try:
            headers['content-type'] = environ['CONTENT_TYPE']
        except KeyError:
            pass

        # Add our host if one isn't defined
        if 'host' not in headers:
            headers['host'] = environ['SERVER_NAME']

        # Make the remote request
        try:

            logger.debug('%s %s %r',
                         environ['REQUEST_METHOD'], path, headers)
            connection.request(environ['REQUEST_METHOD'], path,
                               body=body, headers=headers)
        except Exception as e:
            # We need extra exception handling in the case the server fails
            # in mid connection, it's an edge case but I've seen it
            if isinstance(e, ConnectionRefusedError):
                # The notebook was shutdown by the user
                pass
            else:
                # This might be a genuine error
                logger.exception(e)

            start_response('501 Gateway Error', [('Content-Type', 'text/html')])
            yield '<H1>Could not proxy IPython Notebook running localhost:{}</H1>'.format(self.port).encode("utf-8")
            return

        try:
            response = connection.getresponse()
        except ConnectionResetError:
            # Notebook shutdown
            start_response('501 Gateway Error', [('Content-Type', 'text/html')])
            yield '<H1>Could not proxy IPython Notebook running localhost:{}</H1>'.format(self.port).encode("utf-8")
            return

        hopped_headers = response.getheaders()
        headers = [(key, value)
                   for key, value in hopped_headers
                   if not is_hop_by_hop(key)]

        start_response('{0.status} {0.reason}'.format(response), headers)
        while True:
            chunk = response.read(4096)
            if chunk:
                yield chunk
            else:
                break
187256
def setup(self, environ):
        '''
        '''
        request = wsgi_request(environ)
        cfg = request.cache.cfg
        loop = request.cache._loop
        self.store = create_store(cfg.data_store, loop=loop)
        pubsub = self.store.pubsub(protocol=Protocol())
        channel = '%s_webchat' % self.name
        ensure_future(pubsub.subscribe(channel), loop=loop)
        return WsgiHandler([Router('/', get=self.home_page),
                            WebSocket('/message', Chat(pubsub, channel)),
                            Router('/rpc', post=Rpc(pubsub, channel),
                                   response_content_types=JSON_CONTENT_TYPES)],
                           [AsyncResponseMiddleware,
                            GZipMiddleware(min_length=20)])
293725
def setup_environ(self):
        
        SimpleHandler.setup_environ(self)
        self.environ['ws4py.socket'] = get_connection(self.environ['wsgi.input'])
        self.http_version = self.environ['SERVER_PROTOCOL'].rsplit('/')[-1]
33070
function validateEnvironment(environment, envContext, source = null) {

    // not having an environment is ok
    if (!environment) {
        return;
    }

    Object.keys(environment).forEach(env => {
        if (!envContext.get(env)) {
            const message = `${source}:\n\tEnvironment key "${env}" is unknown\n`;

            throw new Error(message);
        }
    });
}
1053037
def _detect_msgfmt(env):
    
    if 'MSGFMT' in env:
        return env['MSGFMT']
    msgfmt = env.Detect('msgfmt');
    if msgfmt:
        return msgfmt
    raise SCons.Errors.StopError(MsgfmtNotFound, "Could not detect msgfmt")
    return None
605706
def set_environ(inherit=True, append={}):
    
    _environ = {} if not inherit else environ
    for k,v in append.iteritems():
        _environ[k] = v
    return _environ
1087392
def app(environ, start_response):
    
    from wsgi import container

    """Add Environ To Service Container
    Add the environ to the service container. The environ is generated by the
    the WSGI server above and used by a service provider to manipulate the
    incoming requests
    """

    container.bind('Environ', environ)

    """Execute All Service Providers That Require The WSGI Server
    Run all service provider boot methods if the wsgi attribute is true.
    """

    try:
        for provider in container.make('WSGIProviders'):
            container.resolve(provider.boot)
    except Exception as e:
        container.make('ExceptionHandler').load_exception(e)

    """We Are Ready For Launch
    If we have a solid response and not redirecting then we need to return
    a 200 status code along with the data. If we don't, then we'll have
    to return a 302 redirection to where ever the user would like go
    to next.
    """

    start_response(container.make('Request').get_status_code(),
                   container.make('Request').get_and_reset_headers())

    """Final Step
    This will take the data variable from the Service Container and return
    it to the WSGI server.
    """

    return iter([bytes(container.make('Response'), 'utf-8')])
1034631
def call(env)
      @app.call(env)
    rescue Exception => captured_exception
      if allow_handling?(captured_exception)
        PartyFoul::ExceptionHandler.handle(FilteredException.new(captured_exception), env)
      end
      raise captured_exception
    end
429297
def process_message(self, message, *args, **kwargs):
        
        if not message.level in PERSISTENT_MESSAGE_LEVELS:
            return message

        user = kwargs.get("user") or self.get_user()

        try:
            anonymous = user.is_anonymous()
        except TypeError:
            anonymous = user.is_anonymous
        if anonymous:
            raise NotImplementedError('Persistent message levels cannot be used for anonymous users.')
        message_persistent = PersistentMessage()
        message_persistent.level = message.level
        message_persistent.message = message.message
        message_persistent.extra_tags = message.extra_tags
        message_persistent.user = user

        if "expires" in kwargs:
            message_persistent.expires = kwargs["expires"]
        message_persistent.save()
        return None
501045
def build_wsgi_environ_from_event(event):
    """"""
    params = event.get('queryStringParameters')
    environ = EnvironBuilder(method=event.get('httpMethod') or 'GET',
                             path=event.get('path') or '/',
                             headers=event.get('headers') or {},
                             data=event.get('body') or b'',
                             query_string=params or {}).get_environ()
    environ['SERVER_PORT'] = 443
    if 'execute-api' in environ['HTTP_HOST']:
        # this is the API-Gateway hostname, which takes the stage as the first
        # script path component
        environ['SCRIPT_NAME'] = '/' + event['requestContext'].get('stage')
    else:
        # we are using our own hostname, nothing gets added to the script path
        environ['SCRIPT_NAME'] = ''
    environ['wsgi.url_scheme'] = 'https'
    environ['lambda.event'] = event
    return environ
1323556
def _run_env(self):
        
        env = dict(os.environ)
        env.update(
            getattr(self, 'env', {}),
            PYTHONUSERBASE=self.env_path,
            PIP_USER="1",
        )
        self._disable_venv(env)
        return env
971328
def make_wsgi_app(matching, not_found_app=not_found_app):
    
    def wsgi_app(environ, start_response):
        environ['matcha.matching'] = matching
        try:
            matched_case, matched_dict = matching(environ)
        except NotMatched:
            return not_found_app(environ, start_response)
        else:
            environ['matcha.matched_dict'] = matched_dict
            return matched_case(environ, start_response)
    return wsgi_app
1038742
def _main(environ, argv):
    
    options = get_options(argv)
    if options.version:
        return handle_version()
    vexrc = get_vexrc(options, environ)
    # Handle --shell-config as soon as its arguments are available.
    if options.shell_to_configure:
        return handle_shell_config(options.shell_to_configure, vexrc, environ)
    if options.list is not None:
        return handle_list(vexrc.get_ve_base(environ), options.list)

    # Do as much as possible before a possible make, so errors can raise
    # without leaving behind an unused virtualenv.
    # get_virtualenv_name is destructive and must happen before get_command
    cwd = get_cwd(options)
    ve_base = vexrc.get_ve_base(environ)
    ve_name = get_virtualenv_name(options)
    command = get_command(options, vexrc, environ)
    # Either we create ve_path, get it from options.path or find it
    # in ve_base.
    if options.make:
        if options.path:
            make_path = os.path.abspath(options.path)
        else:
            make_path = os.path.abspath(os.path.join(ve_base, ve_name))
        handle_make(environ, options, make_path)
        ve_path = make_path
    elif options.path:
        ve_path = os.path.abspath(options.path)
        if not os.path.exists(ve_path) or not os.path.isdir(ve_path):
            raise exceptions.InvalidVirtualenv(
                "argument for --path is not a directory")
    else:
        try:
            ve_path = get_virtualenv_path(ve_base, ve_name)
        except exceptions.NoVirtualenvName:
            options.print_help()
            raise
    # get_environ has to wait until ve_path is defined, which might
    # be after a make; of course we can't run until we have env.
    env = get_environ(environ, vexrc['env'], ve_path)
    returncode = run(command, env=env, cwd=cwd)
    if options.remove:
        handle_remove(ve_path)
    if returncode is None:
        raise exceptions.InvalidCommand(
            "command not found: {0!r}".format(command[0]))
    return returncode
123650
function checkEnv() {
        async.series([
            function(cb) {
                childProcess.exec(
                    'python -c "import django; print(django.get_version())"',
                    function(err, version) {
                        if (err || !/^1\.7/.test(version)) {
                            return cb(new Error(
                                'Django 1.7 environment is not working'
                            ));
                        }
                        cb();
                    });
            }
        ], function(err) {
            if (err) {
                console.error(chalk.red('\nFATAL: ' + err.message +
                    '\n'));
            }
        });
    }
516278
def access(self, resp, req, environ, request_time):
        
        if not (self.cfg.accesslog or self.cfg.logconfig or self.cfg.syslog):
            return

        msg = self.make_access_message(resp, req, environ, request_time)
        try:
            self.access_log.info(msg)
        except:
            self.error(traceback.format_exc())