예제 #1
0
def _request_uri(environ):
    """Like wsgiref.url.request_uri, except eliminates :80 ports

    Return the full request URI"""
    url = environ['wsgi.url_scheme'] + '://'

    if environ.get('HTTP_HOST'):
        url += environ['HTTP_HOST']
    else:
        url += environ['SERVER_NAME'] + ':' + environ['SERVER_PORT']
    if url.endswith(':80') and environ['wsgi.url_scheme'] == 'http':
        url = url[:-3]
    elif url.endswith(':443') and environ['wsgi.url_scheme'] == 'https':
        url = url[:-4]

    if PY3:  # pragma: no cover
        script_name = bytes_(environ.get('SCRIPT_NAME', '/'), 'latin-1')
        path_info = bytes_(environ.get('PATH_INFO', ''), 'latin-1')
    else:
        script_name = environ.get('SCRIPT_NAME', '/')
        path_info = environ.get('PATH_INFO', '')

    url += url_quote(script_name)
    qpath_info = url_quote(path_info)
    if not 'SCRIPT_NAME' in environ:
        url += qpath_info[1:]
    else:
        url += qpath_info
    return url
예제 #2
0
파일: response.py 프로젝트: nkunal/webob
def _request_uri(environ):
    """Like wsgiref.url.request_uri, except eliminates :80 ports

    Return the full request URI"""
    url = environ['wsgi.url_scheme']+'://'

    if environ.get('HTTP_HOST'):
        url += environ['HTTP_HOST']
    else:
        url += environ['SERVER_NAME'] + ':' + environ['SERVER_PORT']
    if url.endswith(':80') and environ['wsgi.url_scheme'] == 'http':
        url = url[:-3]
    elif url.endswith(':443') and environ['wsgi.url_scheme'] == 'https':
        url = url[:-4]

    if PY3: # pragma: no cover
        script_name = bytes_(environ.get('SCRIPT_NAME', '/'), 'latin-1')
        path_info = bytes_(environ.get('PATH_INFO', ''), 'latin-1')
    else:
        script_name = environ.get('SCRIPT_NAME', '/')
        path_info = environ.get('PATH_INFO', '')

    url += url_quote(script_name)
    qpath_info = url_quote(path_info)
    if not 'SCRIPT_NAME' in environ:
        url += qpath_info[1:]
    else:
        url += qpath_info
    return url
예제 #3
0
파일: response.py 프로젝트: mvidner/webob
def _request_uri(environ):
    """Like wsgiref.url.request_uri, except eliminates :80 ports

    Return the full request URI"""
    url = environ["wsgi.url_scheme"] + "://"

    if environ.get("HTTP_HOST"):
        url += environ["HTTP_HOST"]
    else:
        url += environ["SERVER_NAME"] + ":" + environ["SERVER_PORT"]
    if url.endswith(":80") and environ["wsgi.url_scheme"] == "http":
        url = url[:-3]
    elif url.endswith(":443") and environ["wsgi.url_scheme"] == "https":
        url = url[:-4]

    if PY3:  # pragma: no cover
        script_name = bytes_(environ.get("SCRIPT_NAME", "/"), "latin-1")
        path_info = bytes_(environ.get("PATH_INFO", ""), "latin-1")
    else:
        script_name = environ.get("SCRIPT_NAME", "/")
        path_info = environ.get("PATH_INFO", "")

    url += url_quote(script_name)
    qpath_info = url_quote(path_info)
    if not "SCRIPT_NAME" in environ:
        url += qpath_info[1:]
    else:
        url += qpath_info
    return url
예제 #4
0
def compute_application_url(request):
    virtual = request.environment.get('HTTP_X_VHM_ROOT')
    script_name = request.script_name
    if virtual is not None:
        script_name = script_name.lstrip(virtual)
    bscript_name = bytes_(script_name, request.url_encoding)
    # FIXME : host can be virtual too.
    return request.host_url + url_quote(bscript_name, PATH_SAFE)
def _request_uri(environ):
    """Like wsgiref.url.request_uri, except eliminates :80 ports

    Return the full request URI"""
    url = environ['wsgi.url_scheme']+'://'

    if environ.get('HTTP_HOST'):
        url += environ['HTTP_HOST']
    else:
        url += environ['SERVER_NAME'] + ':' + environ['SERVER_PORT']
    if url.endswith(':80') and environ['wsgi.url_scheme'] == 'http':
        url = url[:-3]
    elif url.endswith(':443') and environ['wsgi.url_scheme'] == 'https':
        url = url[:-4]

    url += url_quote(environ.get('SCRIPT_NAME') or '/')
    path_info = url_quote(environ.get('PATH_INFO',''))
    if not environ.get('SCRIPT_NAME'):
        url += path_info[1:]
    else:
        url += path_info
    return url
예제 #6
0
 def __call__(self, environ, start_response):
     scheme = environ['wsgi.url_scheme']
     if scheme == 'http':
         ConnClass = self.HTTPConnection
     elif scheme == 'https':
         ConnClass = self.HTTPSConnection
     else:
         raise ValueError("Unknown scheme: %r" % scheme)
     if 'SERVER_NAME' not in environ:
         host = environ.get('HTTP_HOST')
         if not host:
             raise ValueError(
                 "environ contains neither SERVER_NAME nor HTTP_HOST")
         if ':' in host:
             host, port = host.split(':', 1)
         else:
             if scheme == 'http':
                 port = '80'
             else:
                 port = '443'
         environ['SERVER_NAME'] = host
         environ['SERVER_PORT'] = port
     kw = {}
     if ('webob.client.timeout' in environ
             and self._timeout_supported(ConnClass)):
         kw['timeout'] = environ['webob.client.timeout']
     conn = ConnClass('%(SERVER_NAME)s:%(SERVER_PORT)s' % environ, **kw)
     headers = {}
     for key, value in environ.items():
         if key.startswith('HTTP_'):
             key = key[5:].replace('_', '-').title()
             headers[key] = value
     path = (url_quote(environ.get('SCRIPT_NAME', '')) +
             url_quote(environ.get('PATH_INFO', '')))
     if environ.get('QUERY_STRING'):
         path += '?' + environ['QUERY_STRING']
     try:
         content_length = int(environ.get('CONTENT_LENGTH', '0'))
     except ValueError:
         content_length = 0
     ## FIXME: there is no streaming of the body, and that might be useful
     ## in some cases
     if content_length:
         body = environ['wsgi.input'].read(content_length)
     else:
         body = ''
     headers['Content-Length'] = content_length
     if environ.get('CONTENT_TYPE'):
         headers['Content-Type'] = environ['CONTENT_TYPE']
     if not path.startswith("/"):
         path = "/" + path
     try:
         conn.request(environ['REQUEST_METHOD'], path, body, headers)
         res = conn.getresponse()
     except socket.timeout:
         resp = exc.HTTPGatewayTimeout()
         return resp(environ, start_response)
     except (socket.error, socket.gaierror) as e:
         if ((isinstance(e, socket.error) and e.args[0] == -2)
                 or (isinstance(e, socket.gaierror) and e.args[0] == 8)):
             # Name or service not known
             resp = exc.HTTPBadGateway(
                 "Name or service not known (bad domain name: %s)" %
                 environ['SERVER_NAME'])
             return resp(environ, start_response)
         elif e.args[0] in _e_refused:  # pragma: no cover
             # Connection refused
             resp = exc.HTTPBadGateway("Connection refused")
             return resp(environ, start_response)
         raise
     headers_out = self.parse_headers(res.msg)
     status = '%s %s' % (res.status, res.reason)
     start_response(status, headers_out)
     length = res.getheader('content-length')
     # FIXME: This shouldn't really read in all the content at once
     if length is not None:
         body = res.read(int(length))
     else:
         body = res.read()
     conn.close()
     return [body]
예제 #7
0
    def __call__(self, environ, start_response):
        method = environ['REQUEST_METHOD']
        if (self.allowed_methods is not None
                and method not in self.allowed_methods):
            return exc.HTTPMethodNotAllowed()(environ, start_response)

        if 'RAW_URI' in environ:
            path_info = environ['RAW_URI']
        elif 'REQUEST_URI' in environ:
            path_info = environ['REQUEST_URI']
        else:
            if self.strip_script_name:
                path_info = ''
            else:
                path_info = environ['SCRIPT_NAME']
            path_info += environ['PATH_INFO']

            if PY3:
                path_info = url_quote(path_info.encode('latin-1'),
                                      LOW_CHAR_SAFE)

            query_string = environ['QUERY_STRING']
            if query_string:
                path_info += '?' + query_string

        for key, dest in self.header_map.items():
            value = environ.get(key)
            if value:
                environ['HTTP_%s' % dest] = value

        host_uri = self.extract_uri(environ)
        uri = host_uri + path_info

        new_headers = {}
        for k, v in environ.items():
            if k.startswith('HTTP_'):
                k = k[5:].replace('_', '-').title()
                new_headers[k] = v

        content_type = environ.get("CONTENT_TYPE")
        if content_type and content_type is not None:
            new_headers['Content-Type'] = content_type

        content_length = environ.get('CONTENT_LENGTH')
        transfer_encoding = environ.get('Transfer-Encoding', '').lower()
        if not content_length and transfer_encoding != 'chunked':
            new_headers['Transfer-Encoding'] = 'chunked'
        elif content_length:
            new_headers['Content-Length'] = content_length

        if new_headers.get('Content-Length', '0') == '-1':
            resp = exc.HTTPInternalServerError(detail=WEBOB_ERROR)
            return resp(environ, start_response)

        try:
            response = self.process_request(uri, method, new_headers, environ)
        except socket.timeout:
            return exc.HTTPGatewayTimeout()(environ, start_response)
        except (socket.error, socket.gaierror):
            return exc.HTTPBadGateway()(environ, start_response)
        except Exception as e:
            self.logger.exception(e)
            return exc.HTTPInternalServerError()(environ, start_response)

        status, location, headerslist, app_iter = response

        if location:
            if self.strip_script_name:
                prefix_path = environ['SCRIPT_NAME']
            else:
                prefix_path = None

            new_location = rewrite_location(host_uri,
                                            location,
                                            prefix_path=prefix_path)

            headers = []
            for k, v in headerslist:
                if k.lower() == 'location':
                    v = new_location
                headers.append((k, v))
        else:
            headers = headerslist

        start_response(status, headers)

        if method == "HEAD":
            return [six.b('')]

        return app_iter
예제 #8
0
파일: proxies.py 프로젝트: gawel/WSGIProxy2
    def __call__(self, environ, start_response):
        method = environ["REQUEST_METHOD"]
        if self.allowed_methods is not None and method not in self.allowed_methods:
            return exc.HTTPMethodNotAllowed()(environ, start_response)

        if "RAW_URI" in environ:
            path_info = environ["RAW_URI"]
        elif "REQUEST_URI" in environ:
            path_info = environ["REQUEST_URI"]
        else:
            if self.strip_script_name:
                path_info = ""
            else:
                path_info = environ["SCRIPT_NAME"]
            path_info += environ["PATH_INFO"]

            if PY3:
                path_info = url_quote(path_info.encode("latin-1"), LOW_CHAR_SAFE)

            query_string = environ["QUERY_STRING"]
            if query_string:
                path_info += "?" + query_string

        for key, dest in self.header_map.items():
            value = environ.get(key)
            if value:
                environ["HTTP_%s" % dest] = value

        host_uri = self.extract_uri(environ)
        uri = host_uri + path_info

        new_headers = {}
        for k, v in environ.items():
            if k.startswith("HTTP_"):
                k = k[5:].replace("_", "-").title()
                new_headers[k] = v

        content_type = environ.get("CONTENT_TYPE")
        if content_type and content_type is not None:
            new_headers["Content-Type"] = content_type

        content_length = environ.get("CONTENT_LENGTH")
        transfer_encoding = environ.get("Transfer-Encoding", "").lower()
        if not content_length and transfer_encoding != "chunked":
            new_headers["Transfer-Encoding"] = "chunked"
        elif content_length:
            new_headers["Content-Length"] = content_length

        if new_headers.get("Content-Length", "0") == "-1":
            resp = exc.HTTPInternalServerError(detail=WEBOB_ERROR)
            return resp(environ, start_response)

        try:
            response = self.process_request(uri, method, new_headers, environ)
        except socket.timeout:
            return exc.HTTPGatewayTimeout()(environ, start_response)
        except (socket.error, socket.gaierror):
            return exc.HTTPBadGateway()(environ, start_response)
        except Exception as e:
            self.logger.exception(e)
            return exc.HTTPInternalServerError()(environ, start_response)

        status, location, headerslist, app_iter = response

        if location:
            if self.strip_script_name:
                prefix_path = environ["SCRIPT_NAME"]
            else:
                prefix_path = None

            new_location = rewrite_location(host_uri, location, prefix_path=prefix_path)

            headers = []
            for k, v in headerslist:
                if k.lower() == "location":
                    v = new_location
                headers.append((k, v))
        else:
            headers = headerslist

        start_response(status, headers)

        if method == "HEAD":
            return [six.b("")]

        return app_iter
예제 #9
0
파일: proxies.py 프로젝트: lrowe/WSGIProxy2
    def __call__(self, environ, start_response):
        method = environ['REQUEST_METHOD']
        if (self.allowed_methods is not None and
                method not in self.allowed_methods):
                return exc.HTTPMethodNotAllowed()(environ, start_response)

        if self.strip_script_name:
            path_info = ''
        else:
            path_info = environ['SCRIPT_NAME']
        path_info += environ['PATH_INFO']

        if PY3:
            path_info = url_quote(path_info.encode('latin-1'), LOW_CHAR_SAFE)

        query_string = environ['QUERY_STRING']
        if query_string:
            path_info += '?' + query_string

        for key, dest in self.header_map.items():
            value = environ.get(key)
            if value:
                environ['HTTP_%s' % dest] = value

        host_uri = self.extract_uri(environ)
        uri = host_uri + path_info

        new_headers = {}
        for k, v in environ.items():
            if k.startswith('HTTP_'):
                k = k[5:].replace('_', '-').title()
                new_headers[k] = v

        content_type = environ.get("CONTENT_TYPE")
        if content_type and content_type is not None:
            new_headers['Content-Type'] = content_type

        content_length = environ.get('CONTENT_LENGTH')
        transfer_encoding = environ.get('Transfer-Encoding', '').lower()
        if not content_length and transfer_encoding != 'chunked':
            new_headers['Transfer-Encoding'] = 'chunked'
        elif content_length:
            new_headers['Content-Length'] = content_length

        if new_headers.get('Content-Length', '0') == '-1':
            resp = exc.HTTPInternalServerError(detail=WEBOB_ERROR)
            return resp(environ, start_response)

        try:
            response = self.process_request(uri, method, new_headers, environ)
        except socket.timeout:
            return exc.HTTPGatewayTimeout()(environ, start_response)
        except (socket.error, socket.gaierror):
            return exc.HTTPBadGateway()(environ, start_response)
        except Exception as e:
            self.logger.exception(e)
            return exc.HTTPInternalServerError()(environ, start_response)

        status, location, headerslist, app_iter = response

        if location:
            if self.strip_script_name:
                prefix_path = environ['SCRIPT_NAME']
            else:
                prefix_path = None

            new_location = rewrite_location(host_uri, location,
                                            prefix_path=prefix_path)

            headers = []
            for k, v in headerslist:
                if k.lower() == 'location':
                    v = new_location
                headers.append((k, v))
        else:
            headers = headerslist

        start_response(status, headers)

        if method == "HEAD":
            return [six.b('')]

        return app_iter
예제 #10
0
파일: client.py 프로젝트: mvidner/webob
 def __call__(self, environ, start_response):
     scheme = environ['wsgi.url_scheme']
     if scheme == 'http':
         ConnClass = httplib.HTTPConnection
     elif scheme == 'https':
         ConnClass = httplib.HTTPSConnection
     else:
         raise ValueError(
             "Unknown scheme: %r" % scheme)
     if 'SERVER_NAME' not in environ:
         host = environ.get('HTTP_HOST')
         if not host:
             raise ValueError(
                 "environ contains neither SERVER_NAME nor HTTP_HOST")
         if ':' in host:
             host, port = host.split(':', 1)
         else:
             if scheme == 'http':
                 port = '80'
             else:
                 port = '443'
         environ['SERVER_NAME'] = host
         environ['SERVER_PORT'] = port
     kw = {}
     if 'webob.client.timeout' in environ and self._timeout_supported(ConnClass):
         kw['timeout'] = environ['webob.client.timeout']
     conn = ConnClass('%(SERVER_NAME)s:%(SERVER_PORT)s' % environ, **kw)
     headers = {}
     for key, value in environ.items():
         if key.startswith('HTTP_'):
             key = key[5:].replace('_', '-').title()
             headers[key] = value
     path = (url_quote(environ.get('SCRIPT_NAME', ''))
             + url_quote(environ.get('PATH_INFO', '')))
     if environ.get('QUERY_STRING'):
         path += '?' + environ['QUERY_STRING']
     try:
         content_length = int(environ.get('CONTENT_LENGTH', '0'))
     except ValueError:
         content_length = 0
     ## FIXME: there is no streaming of the body, and that might be useful
     ## in some cases
     if content_length:
         body = environ['wsgi.input'].read(content_length)
     else:
         body = ''
     headers['Content-Length'] = content_length
     if environ.get('CONTENT_TYPE'):
         headers['Content-Type'] = environ['CONTENT_TYPE']
     if not path.startswith("/"):
         path = "/" + path
     try:
         conn.request(environ['REQUEST_METHOD'],
                      path, body, headers)
         res = conn.getresponse()
     except socket.timeout:
         resp = exc.HTTPGatewayTimeout()
         return resp(environ, start_response)
     except (socket.error, socket.gaierror) as e:
         if ((isinstance(e, socket.error) and e.args[0] == -2) or
             (isinstance(e, socket.gaierror) and e.args[0] == 8)):
             # Name or service not known
             resp = exc.HTTPBadGateway(
                 "Name or service not known (bad domain name: %s)"
                 % environ['SERVER_NAME'])
             return resp(environ, start_response)
         elif e.args[0] in (61, 111):
             # Connection refused
             resp = exc.HTTPBadGateway(
                 "Connection refused")
             return resp(environ, start_response)
         raise
     headers_out = self.parse_headers(res.msg)
     status = '%s %s' % (res.status, res.reason)
     start_response(status, headers_out)
     length = res.getheader('content-length')
     # FIXME: This shouldn't really read in all the content at once
     if length is not None:
         body = res.read(int(length))
     else:
         body = res.read()
     conn.close()
     return [body]
예제 #11
0
 def __call__(self, environ, start_response):
     scheme = environ["wsgi.url_scheme"]
     if scheme == "http":
         ConnClass = self.HTTPConnection
     elif scheme == "https":
         ConnClass = self.HTTPSConnection
     else:
         raise ValueError("Unknown scheme: %r" % scheme)
     if "SERVER_NAME" not in environ:
         host = environ.get("HTTP_HOST")
         if not host:
             raise ValueError(
                 "environ contains neither SERVER_NAME nor HTTP_HOST")
         if ":" in host:
             host, port = host.split(":", 1)
         else:
             if scheme == "http":
                 port = "80"
             else:
                 port = "443"
         environ["SERVER_NAME"] = host
         environ["SERVER_PORT"] = port
     kw = {}
     if "webob.client.timeout" in environ and self._timeout_supported(
             ConnClass):
         kw["timeout"] = environ["webob.client.timeout"]
     conn = ConnClass("%(SERVER_NAME)s:%(SERVER_PORT)s" % environ, **kw)
     headers = {}
     for key, value in environ.items():
         if key.startswith("HTTP_"):
             key = key[5:].replace("_", "-").title()
             headers[key] = value
     path = url_quote(environ.get("SCRIPT_NAME", "")) + url_quote(
         environ.get("PATH_INFO", ""))
     if environ.get("QUERY_STRING"):
         path += "?" + environ["QUERY_STRING"]
     try:
         content_length = int(environ.get("CONTENT_LENGTH", "0"))
     except ValueError:
         content_length = 0
     # FIXME: there is no streaming of the body, and that might be useful
     # in some cases
     if content_length:
         body = environ["wsgi.input"].read(content_length)
     else:
         body = ""
     headers["Content-Length"] = content_length
     if environ.get("CONTENT_TYPE"):
         headers["Content-Type"] = environ["CONTENT_TYPE"]
     if not path.startswith("/"):
         path = "/" + path
     try:
         conn.request(environ["REQUEST_METHOD"], path, body, headers)
         res = conn.getresponse()
     except socket.timeout:
         resp = exc.HTTPGatewayTimeout()
         return resp(environ, start_response)
     except (socket.error, socket.gaierror) as e:
         if (isinstance(e, socket.error)
                 and e.args[0] == -2) or (isinstance(e, socket.gaierror)
                                          and e.args[0] == 8):
             # Name or service not known
             resp = exc.HTTPBadGateway(
                 "Name or service not known (bad domain name: %s)" %
                 environ["SERVER_NAME"])
             return resp(environ, start_response)
         elif e.args[0] in _e_refused:  # pragma: no cover
             # Connection refused
             resp = exc.HTTPBadGateway("Connection refused")
             return resp(environ, start_response)
         raise
     headers_out = self.parse_headers(res.msg)
     status = "%s %s" % (res.status, res.reason)
     start_response(status, headers_out)
     length = res.getheader("content-length")
     # FIXME: This shouldn't really read in all the content at once
     if length is not None:
         body = res.read(int(length))
     else:
         body = res.read()
     conn.close()
     return [body]
예제 #12
0
 def __call__(self, environ, start_response):
     scheme = environ["wsgi.url_scheme"]
     if scheme == "http":
         ConnClass = self.HTTPConnection
     elif scheme == "https":
         ConnClass = self.HTTPSConnection
     else:
         raise ValueError("Unknown scheme: %r" % scheme)
     if "SERVER_NAME" not in environ:
         host = environ.get("HTTP_HOST")
         if not host:
             raise ValueError("environ contains neither SERVER_NAME nor HTTP_HOST")
         if ":" in host:
             host, port = host.split(":", 1)
         else:
             if scheme == "http":
                 port = "80"
             else:
                 port = "443"
         environ["SERVER_NAME"] = host
         environ["SERVER_PORT"] = port
     kw = {}
     if "webob.client.timeout" in environ and self._timeout_supported(ConnClass):
         kw["timeout"] = environ["webob.client.timeout"]
     conn = ConnClass("%(SERVER_NAME)s:%(SERVER_PORT)s" % environ, **kw)
     headers = {}
     for key, value in environ.items():
         if key.startswith("HTTP_"):
             key = key[5:].replace("_", "-").title()
             headers[key] = value
     path = url_quote(environ.get("SCRIPT_NAME", "")) + url_quote(environ.get("PATH_INFO", ""))
     if environ.get("QUERY_STRING"):
         path += "?" + environ["QUERY_STRING"]
     try:
         content_length = int(environ.get("CONTENT_LENGTH", "0"))
     except ValueError:
         content_length = 0
     ## FIXME: there is no streaming of the body, and that might be useful
     ## in some cases
     if content_length:
         body = environ["wsgi.input"].read(content_length)
     else:
         body = ""
     headers["Content-Length"] = content_length
     if environ.get("CONTENT_TYPE"):
         headers["Content-Type"] = environ["CONTENT_TYPE"]
     if not path.startswith("/"):
         path = "/" + path
     try:
         conn.request(environ["REQUEST_METHOD"], path, body, headers)
         res = conn.getresponse()
     except socket.timeout:
         resp = exc.HTTPGatewayTimeout()
         return resp(environ, start_response)
     except (socket.error, socket.gaierror) as e:
         if (isinstance(e, socket.error) and e.args[0] == -2) or (isinstance(e, socket.gaierror) and e.args[0] == 8):
             # Name or service not known
             resp = exc.HTTPBadGateway("Name or service not known (bad domain name: %s)" % environ["SERVER_NAME"])
             return resp(environ, start_response)
         elif e.args[0] in _e_refused:  # pragma: no cover
             # Connection refused
             resp = exc.HTTPBadGateway("Connection refused")
             return resp(environ, start_response)
         raise
     headers_out = self.parse_headers(res.msg)
     status = "%s %s" % (res.status, res.reason)
     start_response(status, headers_out)
     length = res.getheader("content-length")
     # FIXME: This shouldn't really read in all the content at once
     if length is not None:
         body = res.read(int(length))
     else:
         body = res.read()
     conn.close()
     return [body]