Create a WSGI environment from the proxy integration event.
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
7140
def gen_procfile(ctx, wsgi, dev):
    
    if wsgi is None:
        if os.path.exists("wsgi.py"):
            wsgi = "wsgi.py"
        elif os.path.exists("app.py"):
            wsgi = "app.py"
        else:
            wsgi = "app.py"
            ctx.invoke(gen_apppy)

    def write_procfile(filename, server_process, debug):
        processes = [server_process] + current_app.processes
        procfile = []
        for name, cmd in procfile_processes(processes, debug).iteritems():
            procfile.append("%s: %s" % (name, cmd))
        with open(filename, "w") as f:
            f.write("\n".join(procfile))

    write_procfile("Procfile", ("web", ["gunicorn", wsgi]), False)
    if dev:
        write_procfile("Procfile.dev", ("web", ["frasco", "serve"]), True)
1076965
def setup_environment():
  
  absl.logging.set_verbosity(absl.logging.WARNING)

  # The default is HTTP/1.0 for some strange reason. If we don't use
  # HTTP/1.1 then a new TCP socket and Python thread is created for
  # each HTTP request. The tradeoff is we must always specify the
  # Content-Length header, or do chunked encoding for streaming.
  serving.WSGIRequestHandler.protocol_version = 'HTTP/1.1'
194157
def create(self):
        
        self.service.create()

        os.environ[predix.config.get_env_key(self.use_class, 'host')] = self.get_eventhub_host()
        os.environ[predix.config.get_env_key(self.use_class, 'port')] = self.get_eventhub_grpc_port()
        os.environ[predix.config.get_env_key(self.use_class, 'wss_publish_uri')] = self.get_publish_wss_uri()
        os.environ[predix.config.get_env_key(self.use_class, 'zone_id')] = self.get_zone_id()
1316297
def create(self, resource_id=None, attributes=None):
        

        return self.proxy.create(resource_id=resource_id, attributes=attributes)
128247
def get_environ(self):
        """"""
        req = self.req
        env_10 = WSGIGateway_10.get_environ(self)
        env = dict([(k.decode('ISO-8859-1'), v) for k, v in env_10.iteritems()])
        env[u'wsgi.version'] = ('u', 0)
        
        # Request-URI
        env.setdefault(u'wsgi.url_encoding', u'utf-8')
        try:
            for key in [u"PATH_INFO", u"SCRIPT_NAME", u"QUERY_STRING"]:
                env[key] = env_10[str(key)].decode(env[u'wsgi.url_encoding'])
        except UnicodeDecodeError:
            # Fall back to latin 1 so apps can transcode if needed.
            env[u'wsgi.url_encoding'] = u'ISO-8859-1'
            for key in [u"PATH_INFO", u"SCRIPT_NAME", u"QUERY_STRING"]:
                env[key] = env_10[str(key)].decode(env[u'wsgi.url_encoding'])
        
        for k, v in sorted(env.items()):
            if isinstance(v, str) and k not in ('REQUEST_URI', 'wsgi.input'):
                env[k] = v.decode('ISO-8859-1')
        
        return env
1162134
def get_environ(self):
        """"""
        req = self.req
        env = {
            # set a non-standard environ entry so the WSGI app can know what
            # the *real* server protocol is (and what features to support).
            # See http://www.faqs.org/rfcs/rfc2145.html.
            'ACTUAL_SERVER_PROTOCOL': req.server.protocol,
            'PATH_INFO': req.path,
            'QUERY_STRING': req.qs,
            'REMOTE_ADDR': req.conn.remote_addr or '',
            'REMOTE_PORT': str(req.conn.remote_port or ''),
            'REQUEST_METHOD': req.method,
            'REQUEST_URI': req.uri,
            'SCRIPT_NAME': '',
            'SERVER_NAME': req.server.server_name,
            # Bah. "SERVER_PROTOCOL" is actually the REQUEST protocol.
            'SERVER_PROTOCOL': req.request_protocol,
            'SERVER_SOFTWARE': req.server.software,
            'wsgi.errors': sys.stderr,
            'wsgi.input': req.rfile,
            'wsgi.multiprocess': False,
            'wsgi.multithread': True,
            'wsgi.run_once': False,
            'wsgi.url_scheme': req.scheme,
            'wsgi.version': (1, 0),
            }
        
        if isinstance(req.server.bind_addr, basestring):
            # AF_UNIX. This isn't really allowed by WSGI, which doesn't
            # address unix domain sockets. But it's better than nothing.
            env["SERVER_PORT"] = ""
        else:
            env["SERVER_PORT"] = str(req.server.bind_addr[1])
        
        # Request headers
        for k, v in req.inheaders.iteritems():
            env["HTTP_" + k.upper().replace("-", "_")] = v
        
        # CONTENT_TYPE/CONTENT_LENGTH
        ct = env.pop("HTTP_CONTENT_TYPE", None)
        if ct is not None:
            env["CONTENT_TYPE"] = ct
        cl = env.pop("HTTP_CONTENT_LENGTH", None)
        if cl is not None:
            env["CONTENT_LENGTH"] = cl
        
        if req.conn.ssl_env:
            env.update(req.conn.ssl_env)
        
        return env
72745
function _createSandbox(config) {
  if (proxiedGlobal && proxiedGlobal) return workspaces.get(...makeArray(config.workspace));

  const sandbox = {};
  if (config.includeGlobals && (!proxiedGlobal || !config.proxyGlobal)) Object.assign(sandbox, global);

  return vm.createContext(sandbox);
}
735460
def start_wsgi_server(port, addr='', registry=REGISTRY):
    """"""
    app = make_wsgi_app(registry)
    httpd = make_server(addr, port, app, handler_class=_SilentHandler)
    t = threading.Thread(target=httpd.serve_forever)
    t.daemon = True
    t.start()
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)])
847626
def build_environ(scope, message, body):
    
    environ = {
        "REQUEST_METHOD": scope["method"],
        "SCRIPT_NAME": "",
        "PATH_INFO": scope["path"],
        "QUERY_STRING": scope["query_string"].decode("ascii"),
        "SERVER_PROTOCOL": "HTTP/%s" % scope["http_version"],
        "wsgi.version": (1, 0),
        "wsgi.url_scheme": scope.get("scheme", "http"),
        "wsgi.input": io.BytesIO(body),
        "wsgi.errors": sys.stdout,
        "wsgi.multithread": True,
        "wsgi.multiprocess": True,
        "wsgi.run_once": False,
    }

    # Get server name and port - required in WSGI, not in ASGI
    server = scope.get("server", ("localhost", 80))
    environ["SERVER_NAME"] = server[0]
    environ["SERVER_PORT"] = server[1]

    # Get client IP address
    if "client" in scope:
        environ["REMOTE_ADDR"] = scope["client"][0]

    # Go through headers and make them into environ entries
    for name, value in scope.get("headers", []):
        name = name.decode("latin1")
        if name == "content-length":
            corrected_name = "CONTENT_LENGTH"
        elif name == "content-type":
            corrected_name = "CONTENT_TYPE"
        else:
            corrected_name = "HTTP_%s" % name.upper().replace("-", "_")
        # HTTPbis say only ASCII chars are allowed in headers, but we latin1 just in case
        value = value.decode("latin1")
        if corrected_name in environ:
            value = environ[corrected_name] + "," + value
        environ[corrected_name] = value
    return environ
337497
def wsgi_app(self, environ, start_response):
        """"""
        @_LOCAL_MANAGER.middleware
        def _wrapped_app(environ, start_response):
            request = Request(environ)
            setattr(_local, _CURRENT_REQUEST_KEY, request)
            response = self._dispatch_request(request)
            return response(environ, start_response)
        return _wrapped_app(environ, start_response)
176735
def create(self):
        
        self.service.create()

        # Set env vars for immediate use
        zone_id = predix.config.get_env_key(self.use_class, 'zone_id')
        zone = self.service.settings.data['zone']['http-header-value']
        os.environ[zone_id] = zone

        uri = predix.config.get_env_key(self.use_class, 'uri')
        os.environ[uri] = self.service.settings.data['uri']
693396
def from_environ(cls, environ=os.environ):
    """"""
    base_path, unused = (environ['PATH_INFO'].rsplit('/', 1) + [''])[:2]
    return cls(
        environ['HTTP_X_APPENGINE_TASKNAME'],
        environ['HTTP_X_APPENGINE_QUEUENAME'],
        base_path)
713162
def server_bind(self):
        

        try:
            HTTPServer.server_bind(self)
        except Exception as e:
            raise WSGIServerException(e)

        self.setup_environ()
        self.socket.settimeout(1)
757871
def make(env_name, *args, **kwargs):
    """"""
    if env_name not in REGISTERED_ENVS:
        raise Exception(
            "Environment {} not found. Make sure it is a registered environment among: {}".format(
                env_name, ", ".join(REGISTERED_ENVS)
            )
        )
    return REGISTERED_ENVS[env_name](*args, **kwargs)
94302
def wsgi_handler(event, context, app, logger):
    

    environ = build_wsgi_environ_from_event(event)
    wsgi_status = []
    wsgi_headers = []

    logger.info('Processing {} request'.format(environ['REQUEST_METHOD']))

    def start_response(status, headers):
        if len(wsgi_status) or len(wsgi_headers):
            raise RuntimeError('start_response called more than once!')
        wsgi_status.append(status)
        wsgi_headers.append(headers)

    resp = list(app(environ, start_response))
    proxy = {'statusCode': int(wsgi_status[0].split()[0]),
             'headers': {h[0]: h[1] for h in wsgi_headers[0]},
             'body': b''.join(resp).decode('utf-8')}

    logger.info("Returning {}".format(proxy['statusCode']),
                http_status=proxy['statusCode'])

    return proxy