Create a wsgi environment from an apigw request.
4106
def create_wsgi_request(event, server_name='apigw'):
    
    path = urllib.url2pathname(event['path'])
    script_name = (
        event['headers']['Host'].endswith('.amazonaws.com') and
        event['requestContext']['stage'] or '').encode('utf8')
    query = event['queryStringParameters']
    query_string = query and urllib.urlencode(query) or ""
    body = event['body'] and event['body'].encode('utf8') or ''

    environ = {
        'HTTPS': 'on',
        'PATH_INFO': path.encode('utf8'),
        'QUERY_STRING': query_string.encode('utf8'),
        'REMOTE_ADDR': event[
            'requestContext']['identity']['sourceIp'].encode('utf8'),
        'REQUEST_METHOD': event['httpMethod'].encode('utf8'),
        'SCRIPT_NAME': script_name,
        'SERVER_NAME': server_name.encode('utf8'),
        'SERVER_PORT': '80'.encode('utf8'),
        'SERVER_PROTOCOL': u'HTTP/1.1'.encode('utf8'),

        'wsgi.errors': sys.stderr,
        'wsgi.input': StringIO(body),
        'wsgi.multiprocess': False,
        'wsgi.multithread': False,
        'wsgi.run_once': False,
        'wsgi.url_scheme': u'https'.encode('utf8'),
        'wsgi.version': (1, 0),
    }

    headers = event['headers']
    # Input processing
    if event['httpMethod'] in ("POST", "PUT", "PATCH"):
        if 'Content-Type' in headers:
            environ['CONTENT_TYPE'] = headers['Content-Type']
        environ['CONTENT_LENGTH'] = str(len(body))

    for header in list(event['headers'].keys()):
        wsgi_name = "HTTP_" + header.upper().replace('-', '_')
        environ[wsgi_name] = headers[header].encode('utf8')

    if script_name:
        path_info = environ['PATH_INFO']
        if script_name in path_info:
            environ['PATH_INFO'].replace(script_name, '')

    # Extract remote user from event
    remote_user = None
    if event['requestContext'].get('authorizer'):
        remote_user = event[
            'requestContext']['authorizer'].get('principalId')
    elif event['requestContext'].get('identity'):
        remote_user = event['requestContext']['identity'].get('userArn')
    if remote_user:
        environ['REMOTE_USER'] = remote_user

    # apigw aware integrations
    environ['apigw.request'] = event['requestContext']
    environ['apigw.stagevars'] = event['stageVariables']

    return environ
30339
def wsgi(self, environ, start_response):
        
        try:
            environ['bottle.app'] = self
            request.bind(environ)
            response.bind()
            out = self._cast(self._handle(environ), request, response)
            # rfc2616 section 4.3
            if response._status_code in (100, 101, 204, 304)\
            or request.method == 'HEAD':
                if hasattr(out, 'close'): out.close()
                out = []
            start_response(response._status_line, list(response.iter_headers()))
            return out
        except (KeyboardInterrupt, SystemExit, MemoryError):
            raise
        except Exception, e:
            if not self.catchall: raise
            err = '<h1>Critical error while processing request: %s</h1>' \
                  % html_escape(environ.get('PATH_INFO', '/'))
            if DEBUG:
                err += '<h2>Error:</h2>\n<pre>\n%s\n</pre>\n' \
                       '<h2>Traceback:</h2>\n<pre>\n%s\n</pre>\n' \
                       % (html_escape(repr(e)), html_escape(format_exc(10)))
            environ['wsgi.errors'].write(err)
            headers = [('Content-Type', 'text/html; charset=UTF-8')]
            start_response('500 INTERNAL SERVER ERROR', headers)
            return [tob(err)]
753113
def setup(self, environ):
        ''''''
        json_handler = Root().putSubHandler('calc', Calculator())
        middleware = wsgi.Router('/', post=json_handler,
                                 accept_content_types=JSON_CONTENT_TYPES)
        response = [wsgi.GZipMiddleware(200)]
        return wsgi.WsgiHandler(middleware=[wsgi.wait_for_body_middleware,
                                            middleware],
                                response_middleware=response)
455555
def wsgi(self, environ, start_response):
        
        try:
            environ['bottle.app'] = self
            request.bind(environ)
            response.bind()
            out = self._handle(environ)
            out = self._cast(out, request, response)
            # rfc2616 section 4.3
            if response.status in (100, 101, 204, 304) or request.method == 'HEAD':
                if hasattr(out, 'close'): out.close()
                out = []
            status = '%d %s' % (response.status, HTTP_CODES[response.status])
            start_response(status, response.headerlist)
            return out
        except (KeyboardInterrupt, SystemExit, MemoryError):
            raise
        except Exception as e:
            if not self.catchall: raise
            err = '<h1>Critical error while processing request: %s</h1>' \
                  % environ.get('PATH_INFO', '/')
            if DEBUG:
                err += '<h2>Error:</h2>\n<pre>%s</pre>\n' % repr(e)
                err += '<h2>Traceback:</h2>\n<pre>%s</pre>\n' % format_exc(10)
            environ['wsgi.errors'].write(err) #TODO: wsgi.error should not get html
            start_response('500 INTERNAL SERVER ERROR', [('Content-Type', 'text/html')])
            return [tob(err)]
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)
1027781
def wsgi(self, environ, start_response):
        
        try:
            out = self._cast(self._handle(environ))
            # rfc2616 section 4.3
            if response._status_code in (100, 101, 204, 304)\
            or environ['REQUEST_METHOD'] == 'HEAD':
                if hasattr(out, 'close'): out.close()
                out = []
            start_response(response._status_line, response.headerlist)
            return out
        except (KeyboardInterrupt, SystemExit, MemoryError):
            raise
        except Exception:
            if not self.catchall: raise
            err = '<h1>Critical error while processing request: %s</h1>' \
                  % html_escape(environ.get('PATH_INFO', '/'))
            if DEBUG:
                err += '<h2>Error:</h2>\n<pre>\n%s\n</pre>\n' \
                       '<h2>Traceback:</h2>\n<pre>\n%s\n</pre>\n' \
                       % (html_escape(repr(_e())), html_escape(format_exc()))
            environ['wsgi.errors'].write(err)
            headers = [('Content-Type', 'text/html; charset=UTF-8')]
            start_response('500 INTERNAL SERVER ERROR', headers, sys.exc_info())
            return [tob(err)]
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
302179
def sanitize_http_wsgi_env(client, event):
    
    try:
        env = event["context"]["request"]["env"]
        event["context"]["request"]["env"] = varmap(_sanitize, env)
    except (KeyError, TypeError):
        pass
    return event
441920
def get_cgi_fieldstorage_from_wsgi_env(
        env: Dict[str, str],
        include_query_string: bool = True) -> cgi.FieldStorage:
    
    # http://stackoverflow.com/questions/530526/accessing-post-data-from-wsgi
    post_env = env.copy()
    if not include_query_string:
        post_env['QUERY_STRING'] = ''
    form = cgi.FieldStorage(
        fp=env['wsgi.input'],
        environ=post_env,
        keep_blank_values=True
    )
    return form
1099838
def create(self, environments):
        

        data = {'environments_vip': environments}
        uri = 'api/v3/environment-vip/'
        return super(ApiEnvironmentVip, self).post(uri, data)
90530
def start():
    '''
    
    '''
    from wsgiref.simple_server import make_server

    # When started outside of salt-api __opts__ will not be injected
    if '__opts__' not in globals():
        globals()['__opts__'] = get_opts()

        if __virtual__() is False:
            raise SystemExit(1)

    mod_opts = __opts__.get(__virtualname__, {})

    # pylint: disable=C0103
    httpd = make_server('localhost', mod_opts['port'], application)

    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        raise SystemExit(0)
362232
def get(self):
        """"""
        environment_variables_output = [html_for_env_var(key)
                                        for key in sorted(os.environ)]

        cgi_arguments_output = []
        if os.getenv('CONTENT_TYPE') == 'application/x-www-form-urlencoded':
            # Note: a blank Content-type header will still sometimes
            # (in dev_appserver) show up as 'application/x-www-form-urlencoded'
            form = cgi.FieldStorage()
            if not form:
                cgi_arguments_output.append('No CGI arguments given...')
            else:
                for cgi_argument in form:
                    cgi_arguments_output.append(
                            html_for_cgi_argument(cgi_argument, form))
        else:
            data = ''
            cgi_arguments_output.append(STDIN_TEMPLATE.format(len(data)))
            cgi_arguments_output.append(cgi.escape(data))

        modules_api_output = [
            html_for_modules_method('get_current_module_name'),
            html_for_modules_method('get_current_version_name'),
            html_for_modules_method('get_current_instance_id'),
            html_for_modules_method('get_modules'),
            html_for_modules_method('get_versions'),
            html_for_modules_method('get_default_version'),
            html_for_modules_method('get_hostname'),
        ]

        result = PAGE_TEMPLATE.format(
            users.CreateLoginURL(self.request.url),
            users.CreateLogoutURL(self.request.url),
            '<br>\n'.join(environment_variables_output),
            '<br>\n'.join(cgi_arguments_output),
            '<br>\n'.join(modules_api_output),
        )

        self.response.write(result)
435960
def create_ambiente_logico(self):
        """"""
        return AmbienteLogico(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)
20986
def get_wsgi_server(
        self, sock, wsgi_app, protocol=HttpOnlyProtocol, debug=False
    ):
        """"""
        return wsgi.Server(
            sock,
            sock.getsockname(),
            wsgi_app,
            protocol=protocol,
            debug=debug,
            log=getLogger(__name__)
        )
758531
def create_api_environment_vip(self):
        """"""
        return ApiEnvironmentVip(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)
356911
def create_ambiente(self):
        """"""
        return Ambiente(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)
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)