Reconstruct the remote url from the given WSGI ``environ`` dictionary.

    :param environ: the WSGI environment
    :type environ: :class:`collections.MutableMapping`
    :returns: the remote url to proxy
    :rtype: :class:`basestring`
343316
def reconstruct_url(environ, port):
    
    # From WSGI spec, PEP 333
    url = environ.get('PATH_INFO', '')
    if not url.startswith(('http://', 'https://')):
        url = '%s://%s%s' % (
            environ['wsgi.url_scheme'],
            environ['HTTP_HOST'],
            url
        )
    # Fix ;arg=value in url
    if '%3B' in url:
        url, arg = url.split('%3B', 1)
        url = ';'.join([url, arg.replace('%3D', '=')])
    # Stick query string back in
    try:
        query_string = environ['QUERY_STRING']
    except KeyError:
        pass
    else:
        url += '?' + query_string

    parsed = urlparse(url)
    replaced = parsed._replace(netloc="localhost:{}".format(port))
    url = urlunparse(replaced)
    environ['reconstructed_url'] = url
    return url
1271377
def remote_ip
      return @env[Merb::Const::HTTP_CLIENT_IP] if @env.include?(Merb::Const::HTTP_CLIENT_IP)

      if @env.include?(Merb::Const::HTTP_X_FORWARDED_FOR) then
        remote_ips = @env[Merb::Const::HTTP_X_FORWARDED_FOR].split(',').reject do |ip|
          ip =~ Merb::Const::LOCAL_IP_REGEXP
        end

        return remote_ips.first.strip unless remote_ips.empty?
      end

      return @env[Merb::Const::REMOTE_ADDR]
    end
774463
def prepare_env(cls):
        
        os.environ['PATH'] = cls.get_env_path()
        return os.path.basename(Finder.python())
757813
def get_proxies_from_environ():
    """"""
    proxies = {}
    http_proxy = os.getenv('http_proxy') or os.getenv('HTTP_PROXY')
    https_proxy = os.getenv('https_proxy') or os.getenv('HTTPS_PROXY')
    if http_proxy:
        proxies['http'] = http_proxy
    if https_proxy:
        proxies['https'] = https_proxy
    return proxies
846511
def construct_came_from(environ):
    

    came_from = environ.get("PATH_INFO")
    qstr = environ.get("QUERY_STRING", "")
    if qstr:
        came_from += "?" + qstr
    return came_from
1218470
def extract(environ, empty=False, err=False):
    
    formdata = cgi.parse(environ['wsgi.input'], environ, empty, err)
    # Remove single entries from lists
    for key, value in iter(formdata.items()):
        if len(value) == 1:
            formdata[key] = value[0]
    return formdata
358552
def get_environ(self, sock):
        """"""
        cipher = sock.cipher()
        ssl_environ = {
            "wsgi.url_scheme": "https",
            "HTTPS": "on",
            'SSL_PROTOCOL': cipher[1],
            'SSL_CIPHER': cipher[0]
##            SSL_VERSION_INTERFACE 	string 	The mod_ssl program version
##            SSL_VERSION_LIBRARY 	string 	The OpenSSL program version
            }
        return ssl_environ
1139677
def get_d1_env_by_base_url(cn_base_url):
    """"""
    for k, v in D1_ENV_DICT:
        if v['base_url'].startswith(cn_base_url):
            return D1_ENV_DICT[k]
881628
def bind_to_env(self, bound_env):
        '''
        
        '''
        return self.__class__(self._scope, self._location,
                              path=self._path, host=self._host,
                              fragment=self._fragment,
                              ready=self._ready,
                              need_arguments=self._need_arguments,
                              finalize_params=self._finalize_params,
                              parent=self._parent,
                              bound_env=bound_env)
848660
def _load_from_environ(metadata, value_func=None):
    
    # We'll match the ennvar name against the metadata's name. The ennvar
    # name must be uppercase and hyphens in names converted to underscores.
    #
    # | envar       | name    | matches? |
    # +-------------+---------+----------+
    # | FOO_BAR     | foo     | yes      |
    # | FOO_BAR     | bar     | no       |
    # | foo_bar     | bar     | no       |
    # | FOO_BAR_BAZ | foo_bar | yes      |
    # | FOO_BAR_BAZ | foo-bar | yes      |
    # +-------------+---------+----------+

    prefix = metadata.name.upper().replace("-", "_")

    return expand_config(
        environ,
        separator="__",
        skip_to=1,
        key_parts_filter=lambda key_parts: len(key_parts) > 1 and key_parts[0] == prefix,
        value_func=lambda value: value_func(value) if value_func else value,
    )
770283
def _include_paths_from_environ(env_prefix=''):
    """"""
    paths = os.environ.get(env_prefix + 'WSGI_AUTH_PATHS')
    if not paths:
        return []
    return paths.split(';')
956545
def parse_from_environ(self, environ):
        
        content_type = environ.get("CONTENT_TYPE", "")
        content_length = get_content_length(environ)
        mimetype, options = parse_options_header(content_type)
        return self.parse(get_input_stream(environ), mimetype, content_length, options)
1035071
def get_host(environ):
    # type: (Dict[str, str]) -> str
    """"""
    if environ.get("HTTP_HOST"):
        rv = environ["HTTP_HOST"]
        if environ["wsgi.url_scheme"] == "http" and rv.endswith(":80"):
            rv = rv[:-3]
        elif environ["wsgi.url_scheme"] == "https" and rv.endswith(":443"):
            rv = rv[:-4]
    elif environ.get("SERVER_NAME"):
        rv = environ["SERVER_NAME"]
        if (environ["wsgi.url_scheme"], environ["SERVER_PORT"]) not in (
            ("https", "443"),
            ("http", "80"),
        ):
            rv += ":" + environ["SERVER_PORT"]
    else:
        # In spite of the WSGI spec, SERVER_NAME might not be present.
        rv = "unknown"

    return rv
1031858
def environ(on=os, **kw):
    
    
    originals = list()
    
    for key in kw:
        originals.append((key, on.environ.get(key, None)))
        on.environ[key] = kw[key]
    
    yield
    
    for key, value in originals:
        if not value:
            del on.environ[key]
            continue
        
        on.environ[key] = value
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
515013
def _base_environ(self, **request):
        '''
            
        '''
        # This is a minimal valid WSGI environ dictionary, plus:
        # - HTTP_COOKIE: for cookie support,
        # - REMOTE_ADDR: often useful, see #8551.
        # See http://www.python.org/dev/peps/pep-3333/#environ-variables

        environ = {
            'HTTP_COOKIE': self.cookies.output(header='', sep='; '),
            'PATH_INFO': str('/'),
            'REMOTE_ADDR': str('127.0.0.1'),
            'REQUEST_METHOD': str('GET'),
            'SCRIPT_NAME': str(''),
            'SERVER_NAME': str('localhost'),
            'SERVER_PORT': str('8000'),
            'SERVER_PROTOCOL': str('HTTP/1.1'),
            'wsgi.version': (1, 0),
            'wsgi.url_scheme': str('http'),
            'wsgi.input': FakePayload(b''),
            'wsgi.errors': self.errors,
            'wsgi.multiprocess': True,
            'wsgi.multithread': True,
            'wsgi.run_once': False,
        }
        environ.update(self.defaults)
        environ.update(request)
        return environ
389670
def resolve(self, space_id=None, environment_id=None):
        

        proxy_method = getattr(
            self._client,
            base_path_for(self.link_type)
        )
        if self.link_type == 'Space':
            return proxy_method().find(self.id)
        elif environment_id is not None:
            return proxy_method(space_id, environment_id).find(self.id)
        else:
            return proxy_method(space_id).find(self.id)