Esempio n. 1
0
def run_wsgi_app(app, environ, buffered = False):
    environ = _get_environ(environ)
    response = []
    buffer = []

    def start_response(status, headers, exc_info = None):
        if exc_info is not None:
            raise exc_info[0], exc_info[1], exc_info[2]
        response[:] = [status, headers]
        return buffer.append

    app_iter = app(environ, start_response)
    if buffered:
        close_func = getattr(app_iter, 'close', None)
        try:
            app_iter = list(app_iter)
        finally:
            if close_func is not None:
                close_func()

    else:
        while not response:
            buffer.append(app_iter.next())

        if buffer:
            close_func = getattr(app_iter, 'close', None)
            app_iter = chain(buffer, app_iter)
            if close_func is not None:
                app_iter = ClosingIterator(app_iter, close_func)
    return (app_iter, response[0], response[1])
Esempio n. 2
0
def run_wsgi_app(app, environ, buffered=False):
    environ = _get_environ(environ)
    response = []
    buffer = []

    def start_response(status, headers, exc_info=None):
        if exc_info is not None:
            raise exc_info[0], exc_info[1], exc_info[2]
        response[:] = [status, headers]
        return buffer.append

    app_iter = app(environ, start_response)
    if buffered:
        close_func = getattr(app_iter, 'close', None)
        try:
            app_iter = list(app_iter)
        finally:
            if close_func is not None:
                close_func()

    else:
        while not response:
            buffer.append(app_iter.next())

        if buffer:
            close_func = getattr(app_iter, 'close', None)
            app_iter = chain(buffer, app_iter)
            if close_func is not None:
                app_iter = ClosingIterator(app_iter, close_func)
    return (app_iter, response[0], response[1])
Esempio n. 3
0
File: routing.py Progetto: Reve/eve
 def bind_to_environ(self, environ, server_name=None, subdomain=None):
     environ = _get_environ(environ)
     if server_name is None:
         if "HTTP_HOST" in environ:
             server_name = environ["HTTP_HOST"]
         else:
             server_name = environ["SERVER_NAME"]
             if (environ["wsgi.url_scheme"], environ["SERVER_PORT"]) not in (("https", "443"), ("http", "80")):
                 server_name += ":" + environ["SERVER_PORT"]
     elif subdomain is None:
         wsgi_server_name = environ.get("HTTP_HOST", environ["SERVER_NAME"])
         cur_server_name = wsgi_server_name.split(":", 1)[0].split(".")
         real_server_name = server_name.split(":", 1)[0].split(".")
         offset = -len(real_server_name)
         if cur_server_name[offset:] != real_server_name:
             raise ValueError(
                 "the server name provided (%r) does not match the server name from the WSGI environment (%r)"
                 % (server_name, wsgi_server_name)
             )
         subdomain = ".".join(filter(None, cur_server_name[:offset]))
     return Map.bind(
         self,
         server_name,
         environ.get("SCRIPT_NAME"),
         subdomain,
         environ["wsgi.url_scheme"],
         environ["REQUEST_METHOD"],
         environ.get("PATH_INFO"),
     )
Esempio n. 4
0
 def make_conditional(self, request_or_environ):
     environ = _get_environ(request_or_environ)
     if environ['REQUEST_METHOD'] in ('GET', 'HEAD'):
         self.headers['Date'] = http_date()
         if 'content-length' in self.headers:
             self.headers['Content-Length'] = len(self.data)
         if not is_resource_modified(environ, self.headers.get('etag'), None, self.headers.get('last-modified')):
             self.status_code = 304
     return self
Esempio n. 5
0
 def make_conditional(self, request_or_environ):
     environ = _get_environ(request_or_environ)
     if environ['REQUEST_METHOD'] in ('GET', 'HEAD'):
         self.headers['Date'] = http_date()
         if 'content-length' in self.headers:
             self.headers['Content-Length'] = len(self.data)
         if not is_resource_modified(environ, self.headers.get('etag'), None, self.headers.get('last-modified')):
             self.status_code = 304
     return self
Esempio n. 6
0
File: wrappers.py Progetto: Reve/eve
 def make_conditional(self, request_or_environ):
     environ = _get_environ(request_or_environ)
     if environ["REQUEST_METHOD"] in ("GET", "HEAD"):
         self.headers["Date"] = http_date()
         if "content-length" in self.headers:
             self.headers["Content-Length"] = len(self.data)
         if not is_resource_modified(environ, self.headers.get("etag"), None, self.headers.get("last-modified")):
             self.status_code = 304
     return self
 def get_response(self, environ):
     """Get a response object.
     
     :param environ: the environ for the request.
     :return: a :class:`BaseResponse` object or a subclass thereof.
     """
     environ = _get_environ(environ)
     from werkzeug.wrappers import BaseResponse
     headers = self.get_headers(environ)
     return BaseResponse(self.get_body(environ), self.code, headers)
Esempio n. 8
0
def run_wsgi_app(app, environ, buffered=False):
    """Return a tuple in the form (app_iter, status, headers) of the
    application output.  This works best if you pass it an application that
    returns an iterator all the time.

    Sometimes applications may use the `write()` callable returned
    by the `start_response` function.  This tries to resolve such edge
    cases automatically.  But if you don't get the expected output you
    should set `buffered` to `True` which enforces buffering.

    If passed an invalid WSGI application the behavior of this function is
    undefined.  Never pass non-conforming WSGI applications to this function.

    :param app: the application to execute.
    :param buffered: set to `True` to enforce buffering.
    :return: tuple in the form ``(app_iter, status, headers)``
    """
    environ = _get_environ(environ)
    response = []
    buffer = []

    def start_response(status, headers, exc_info=None):
        if exc_info is not None:
            reraise(*exc_info)
        response[:] = [status, headers]
        return buffer.append

    app_rv = app(environ, start_response)
    close_func = getattr(app_rv, 'close', None)
    app_iter = iter(app_rv)

    # when buffering we emit the close call early and convert the
    # application iterator into a regular list
    if buffered:
        try:
            app_iter = list(app_iter)
        finally:
            if close_func is not None:
                close_func()

    # otherwise we iterate the application iter until we have a response, chain
    # the already received data with the already collected data and wrap it in
    # a new `ClosingIterator` if we need to restore a `close` callable from the
    # original return value.
    else:
        for item in app_iter:
            buffer.append(item)
            if response:
                break
        if buffer:
            app_iter = chain(buffer, app_iter)
        if close_func is not None and app_iter is not app_rv:
            app_iter = ClosingIterator(app_iter, close_func)

    return app_iter, response[0], Headers(response[1])
Esempio n. 9
0
def run_wsgi_app(app, environ, buffered=False):
    """Return a tuple in the form (app_iter, status, headers) of the
    application output.  This works best if you pass it an application that
    returns an iterator all the time.

    Sometimes applications may use the `write()` callable returned
    by the `start_response` function.  This tries to resolve such edge
    cases automatically.  But if you don't get the expected output you
    should set `buffered` to `True` which enforces buffering.

    If passed an invalid WSGI application the behavior of this function is
    undefined.  Never pass non-conforming WSGI applications to this function.

    :param app: the application to execute.
    :param buffered: set to `True` to enforce buffering.
    :return: tuple in the form ``(app_iter, status, headers)``
    """
    environ = _get_environ(environ)
    response = []
    buffer = []

    def start_response(status, headers, exc_info=None):
        if exc_info is not None:
            reraise(*exc_info)
        response[:] = [status, headers]
        return buffer.append

    app_rv = app(environ, start_response)
    close_func = getattr(app_rv, 'close', None)
    app_iter = iter(app_rv)

    # when buffering we emit the close call early and convert the
    # application iterator into a regular list
    if buffered:
        try:
            app_iter = list(app_iter)
        finally:
            if close_func is not None:
                close_func()

    # otherwise we iterate the application iter until we have a response, chain
    # the already received data with the already collected data and wrap it in
    # a new `ClosingIterator` if we need to restore a `close` callable from the
    # original return value.
    else:
        for item in app_iter:
            buffer.append(item)
            if response:
                break
        if buffer:
            app_iter = chain(buffer, app_iter)
        if close_func is not None and app_iter is not app_rv:
            app_iter = ClosingIterator(app_iter, close_func)

    return app_iter, response[0], Headers(response[1])
Esempio n. 10
0
def run_wsgi_app(app, environ, buffered=False):
    """返回一个应用输出的元组形式 (app_iter, status, headers)。如果你通过应用
    返回一个迭代器他将会工作的更好。

    有时应用可以使用 `start_ewsponse` 返回的 `write()` 回调函数。这将会自动解
    决边界情况。如果没有得到预期输出,你应该将 `buffered` 设为 `True` 执行
    buffering

    如果传入一个错误的应用,这个函数将会是未定义的。不要给这个函数传入一个不标准
    的 WSGI 应用。

    :param app: 要执行的应用。
    :param buffered: 设为 `True` 来执行 buffering.
    :return: 元组形式 ``(app_iter, status, headers)``
    """
    environ = _get_environ(environ)
    response = []
    buffer = []

    def start_response(status, headers, exc_info=None):
        if exc_info is not None:
            reraise(*exc_info)
        response[:] = [status, headers]
        return buffer.append

    app_iter = app(environ, start_response)

    # when buffering we emit the close call early and convert the
    # application iterator into a regular list
    if buffered:
        close_func = getattr(app_iter, 'close', None)
        try:
            app_iter = list(app_iter)
        finally:
            if close_func is not None:
                close_func()

    # otherwise we iterate the application iter until we have
    # a response, chain the already received data with the already
    # collected data and wrap it in a new `ClosingIterator` if
    # we have a close callable.
    else:
        while not response:
            buffer.append(next(app_iter))
        if buffer:
            close_func = getattr(app_iter, 'close', None)
            app_iter = chain(buffer, app_iter)
            if close_func is not None:
                app_iter = ClosingIterator(app_iter, close_func)

    return app_iter, response[0], Headers(response[1])
Esempio n. 11
0
def run_wsgi_app(app, environ, buffered=False):
    """返回一个应用输出的元组形式 (app_iter, status, headers)。如果你通过应用
    返回一个迭代器他将会工作的更好。

    有时应用可以使用 `start_ewsponse` 返回的 `write()` 回调函数。这将会自动解
    决边界情况。如果没有得到预期输出,你应该将 `buffered` 设为 `True` 执行
    buffering

    如果传入一个错误的应用,这个函数将会是未定义的。不要给这个函数传入一个不标准
    的 WSGI 应用。

    :param app: 要执行的应用。
    :param buffered: 设为 `True` 来执行 buffering.
    :return: 元组形式 ``(app_iter, status, headers)``
    """
    environ = _get_environ(environ)
    response = []
    buffer = []

    def start_response(status, headers, exc_info=None):
        if exc_info is not None:
            reraise(*exc_info)
        response[:] = [status, headers]
        return buffer.append

    app_iter = app(environ, start_response)

    # when buffering we emit the close call early and convert the
    # application iterator into a regular list
    if buffered:
        close_func = getattr(app_iter, "close", None)
        try:
            app_iter = list(app_iter)
        finally:
            if close_func is not None:
                close_func()

    # otherwise we iterate the application iter until we have
    # a response, chain the already received data with the already
    # collected data and wrap it in a new `ClosingIterator` if
    # we have a close callable.
    else:
        while not response:
            buffer.append(next(app_iter))
        if buffer:
            close_func = getattr(app_iter, "close", None)
            app_iter = chain(buffer, app_iter)
            if close_func is not None:
                app_iter = ClosingIterator(app_iter, close_func)

    return app_iter, response[0], Headers(response[1])
Esempio n. 12
0
    def get_response(self, environ):
        """Get a response object.

        :param environ: the environ for the request.
        :return: a :class:`BaseResponse` object or a subclass thereof.
        """
        # lazily imported for various reasons.  For one, we can use the exceptions
        # with custom responses (testing exception instances against types) and
        # so we don't ever have to import the wrappers, but also because there
        # are circular dependencies when bootstrapping the module.
        environ = _get_environ(environ)
        from werkzeug.wrappers import BaseResponse
        headers = self.get_headers(environ)
        return BaseResponse(self.get_body(environ), self.code, headers)
Esempio n. 13
0
    def get_response(self, environ):
        """Get a response object.

        :param environ: the environ for the request.
        :return: a :class:`BaseResponse` object or a subclass thereof.
        """
        # lazily imported for various reasons.  For one, we can use the exceptions
        # with custom responses (testing exception instances against types) and
        # so we don't ever have to import the wrappers, but also because there
        # are circular dependencies when bootstrapping the module.
        environ = _get_environ(environ)
        from werkzeug.wrappers import BaseResponse
        headers = self.get_headers(environ)
        return BaseResponse(self.get_body(environ), self.code, headers)
Esempio n. 14
0
    def get_response(self, environ=None):
        """Get a response object.  If one was passed to the exception
        it's returned directly.

        :param environ: the optional environ for the request.  This
                        can be used to modify the response depending
                        on how the request looked like.
        :return: a :class:`Response` object or a subclass thereof.
        """
        if self.response is not None:
            return self.response
        if environ is not None:
            environ = _get_environ(environ)
        headers = self.get_headers(environ)
        return Response(self.get_body(environ), self.code, headers)
Esempio n. 15
0
    def get_response(self, environ=None):
        """Get a response object.  If one was passed to the exception
        it's returned directly.

        :param environ: the optional environ for the request.  This
                        can be used to modify the response depending
                        on how the request looked like.
        :return: a :class:`Response` object or a subclass thereof.
        """
        if self.response is not None:
            return self.response
        if environ is not None:
            environ = _get_environ(environ)
        headers = self.get_headers(environ)
        return Response(self.get_body(environ), self.code, headers)
Esempio n. 16
0
def run_wsgi_app(app, environ, buffered=False):
    """Return a tuple in the form (app_iter, status, headers) of the
    application output.  This works best if you pass it an application that
    returns an iterator all the time.
    
    Sometimes applications may use the `write()` callable returned
    by the `start_response` function.  This tries to resolve such edge
    cases automatically.  But if you don't get the expected output you
    should set `buffered` to `True` which enforces buffering.
    
    If passed an invalid WSGI application the behavior of this function is
    undefined.  Never pass non-conforming WSGI applications to this function.
    
    :param app: the application to execute.
    :param buffered: set to `True` to enforce buffering.
    :return: tuple in the form ``(app_iter, status, headers)``
    """
    environ = _get_environ(environ)
    response = []
    buffer = []

    def start_response(status, headers, exc_info=None):
        if exc_info is not None:
            raise exc_info[0], exc_info[1], exc_info[2]
        response[:] = [status, headers]
        return buffer.append

    app_iter = app(environ, start_response)
    if buffered:
        close_func = getattr(app_iter, 'close', None)
        try:
            app_iter = list(app_iter)
        finally:
            if close_func is not None:
                close_func()

    else:
        while not response:
            buffer.append(app_iter.next())

        if buffer:
            close_func = getattr(app_iter, 'close', None)
            app_iter = chain(buffer, app_iter)
            if close_func is not None:
                app_iter = ClosingIterator(app_iter, close_func)
    return (app_iter, response[0], response[1])
Esempio n. 17
0
 def bind_to_environ(self, environ, server_name = None, subdomain = None):
     environ = _get_environ(environ)
     if server_name is None:
         if 'HTTP_HOST' in environ:
             server_name = environ['HTTP_HOST']
         else:
             server_name = environ['SERVER_NAME']
             if (environ['wsgi.url_scheme'], environ['SERVER_PORT']) not in (('https', '443'), ('http', '80')):
                 server_name += ':' + environ['SERVER_PORT']
     elif subdomain is None:
         wsgi_server_name = environ.get('HTTP_HOST', environ['SERVER_NAME'])
         cur_server_name = wsgi_server_name.split(':', 1)[0].split('.')
         real_server_name = server_name.split(':', 1)[0].split('.')
         offset = -len(real_server_name)
         if cur_server_name[offset:] != real_server_name:
             raise ValueError('the server name provided (%r) does not match the server name from the WSGI environment (%r)' % (server_name, wsgi_server_name))
         subdomain = '.'.join(filter(None, cur_server_name[:offset]))
     return Map.bind(self, server_name, environ.get('SCRIPT_NAME'), subdomain, environ['wsgi.url_scheme'], environ['REQUEST_METHOD'], environ.get('PATH_INFO'))
Esempio n. 18
0
 def bind_to_environ(self, environ, server_name = None, subdomain = None):
     environ = _get_environ(environ)
     if server_name is None:
         if 'HTTP_HOST' in environ:
             server_name = environ['HTTP_HOST']
         else:
             server_name = environ['SERVER_NAME']
             if (environ['wsgi.url_scheme'], environ['SERVER_PORT']) not in (('https', '443'), ('http', '80')):
                 server_name += ':' + environ['SERVER_PORT']
     elif subdomain is None:
         wsgi_server_name = environ.get('HTTP_HOST', environ['SERVER_NAME'])
         cur_server_name = wsgi_server_name.split(':', 1)[0].split('.')
         real_server_name = server_name.split(':', 1)[0].split('.')
         offset = -len(real_server_name)
         if cur_server_name[offset:] != real_server_name:
             raise ValueError('the server name provided (%r) does not match the server name from the WSGI environment (%r)' % (server_name, wsgi_server_name))
         subdomain = '.'.join(filter(None, cur_server_name[:offset]))
     return Map.bind(self, server_name, environ.get('SCRIPT_NAME'), subdomain, environ['wsgi.url_scheme'], environ['REQUEST_METHOD'], environ.get('PATH_INFO'))
Esempio n. 19
0
    def make_conditional(self, request_or_environ):
        """Make the response conditional to the request.  This method works
        best if an etag was defined for the response already.  The `add_etag`
        method can be used to do that.  If called without etag just the date
        header is set.

        This does nothing if the request method in the request or environ is
        anything but GET or HEAD.

        It does not remove the body of the response because that's something
        the :meth:`__call__` function does for us automatically.

        Returns self so that you can do ``return resp.make_conditional(req)``
        but modifies the object in-place.

        :param request_or_environ: a request object or WSGI environment to be
                                   used to make the response conditional
                                   against.
        """
        environ = _get_environ(request_or_environ)
        if environ['REQUEST_METHOD'] in ('GET', 'HEAD'):
            # if the date is not in the headers, add it now.  We however
            # will not override an already existing header.  Unfortunately
            # this header will be overriden by many WSGI servers including
            # wsgiref.
            if 'date' not in self.headers:
                self.headers['Date'] = http_date()
            if (
                self.automatically_set_content_length and
                'content-length' not in self.headers
            ):
                length = self.calculate_content_length()
                if length is not None:
                    self.headers['Content-Length'] = length
            if not is_resource_modified(
                    environ, self.headers.get('etag'),
                    None, self.headers.get('last-modified')):
                self.status_code = 304
        return self
Esempio n. 20
0
 def get_response(self, environ):
     environ = _get_environ(environ)
     from werkzeug.wrappers import BaseResponse
     headers = self.get_headers(environ)
     return BaseResponse(self.get_body(environ), self.code, headers)
Esempio n. 21
0
    def make_conditional(
        self,
        request_or_environ: "WSGIEnvironment",
        accept_ranges: t.Union[bool, str] = False,
        complete_length: t.Optional[int] = None,
    ) -> "Response":
        """Make the response conditional to the request.  This method works
        best if an etag was defined for the response already.  The `add_etag`
        method can be used to do that.  If called without etag just the date
        header is set.

        This does nothing if the request method in the request or environ is
        anything but GET or HEAD.

        For optimal performance when handling range requests, it's recommended
        that your response data object implements `seekable`, `seek` and `tell`
        methods as described by :py:class:`io.IOBase`.  Objects returned by
        :meth:`~werkzeug.wsgi.wrap_file` automatically implement those methods.

        It does not remove the body of the response because that's something
        the :meth:`__call__` function does for us automatically.

        Returns self so that you can do ``return resp.make_conditional(req)``
        but modifies the object in-place.

        :param request_or_environ: a request object or WSGI environment to be
                                   used to make the response conditional
                                   against.
        :param accept_ranges: This parameter dictates the value of
                              `Accept-Ranges` header. If ``False`` (default),
                              the header is not set. If ``True``, it will be set
                              to ``"bytes"``. If ``None``, it will be set to
                              ``"none"``. If it's a string, it will use this
                              value.
        :param complete_length: Will be used only in valid Range Requests.
                                It will set `Content-Range` complete length
                                value and compute `Content-Length` real value.
                                This parameter is mandatory for successful
                                Range Requests completion.
        :raises: :class:`~werkzeug.exceptions.RequestedRangeNotSatisfiable`
                 if `Range` header could not be parsed or satisfied.

        .. versionchanged:: 2.0
            Range processing is skipped if length is 0 instead of
            raising a 416 Range Not Satisfiable error.
        """
        environ = _get_environ(request_or_environ)
        if environ["REQUEST_METHOD"] in ("GET", "HEAD"):
            # if the date is not in the headers, add it now.  We however
            # will not override an already existing header.  Unfortunately
            # this header will be overriden by many WSGI servers including
            # wsgiref.
            if "date" not in self.headers:
                self.headers["Date"] = http_date()
            accept_ranges = _clean_accept_ranges(accept_ranges)
            is206 = self._process_range_request(environ, complete_length,
                                                accept_ranges)
            if not is206 and not is_resource_modified(
                    environ,
                    self.headers.get("etag"),
                    None,
                    self.headers.get("last-modified"),
            ):
                if parse_etags(environ.get("HTTP_IF_MATCH")):
                    self.status_code = 412
                else:
                    self.status_code = 304
            if (self.automatically_set_content_length
                    and "content-length" not in self.headers):
                length = self.calculate_content_length()
                if length is not None:
                    self.headers["Content-Length"] = length
        return self
Esempio n. 22
0
 def get_description(self, environ):
     environ = _get_environ(environ)
     return self.description
Esempio n. 23
0
 def get_response(self, environ):
     environ = _get_environ(environ)
     from werkzeug.wrappers import BaseResponse
     headers = self.get_headers(environ)
     return BaseResponse(self.get_body(environ), self.code, headers)
 def get_response(self, environ):
     environ = _get_environ(environ) #UGH!
     headers = self.rewritten_headers(environ)
     return BaseResponse(self.get_body(environ), self.code, headers)
Esempio n. 25
0
 def get_description(self, environ):
     """Get the description."""
     environ = _get_environ(environ)
     return self.description
Esempio n. 26
0
 def get_description(self, environ):
     """Get the description."""
     environ = _get_environ(environ)
     return '<p>%s</p>' % escape(self.description)
Esempio n. 27
0
 def get_description(self, environ):
     """Get the description."""
     environ = _get_environ(environ)
     return self.description
Esempio n. 28
0
    def bind_to_environ(self,
                        environ,
                        server_name=None,
                        subdomain=None,
                        request=None,
                        version_dict=None):
        environ = _get_environ(environ)

        if 'HTTP_HOST' in environ:
            wsgi_server_name = environ['HTTP_HOST']

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

            if (environ['wsgi.url_scheme'],
                    environ['SERVER_PORT']) not in (('https', '443'), ('http',
                                                                       '80')):
                wsgi_server_name += ':' + environ['SERVER_PORT']

        wsgi_server_name = wsgi_server_name.lower()

        if server_name is None:
            server_name = wsgi_server_name
        else:
            server_name = server_name.lower()

        if subdomain is None and not self.host_matching:
            cur_server_name = wsgi_server_name.split('.')
            real_server_name = server_name.split('.')
            offset = -len(real_server_name)
            if cur_server_name[offset:] != real_server_name:
                subdomain = '<invalid>'
            else:
                subdomain = '.'.join(filter(None, cur_server_name[:offset]))

        def _get_wsgi_string(name):
            val = environ.get(name)
            if val is not None:
                return wsgi_decoding_dance(val, self.charset)

        script_name = _get_wsgi_string('SCRIPT_NAME')
        path_info = _get_wsgi_string('PATH_INFO')
        query_args = _get_wsgi_string('QUERY_STRING')
        return MFMap.bind(self,
                          server_name,
                          script_name,
                          subdomain,
                          environ['wsgi.url_scheme'],
                          environ['REQUEST_METHOD'],
                          path_info,
                          query_args=query_args,
                          request=request,
                          version_dict=version_dict)
Esempio n. 29
0
 def get_description(self, environ):
     environ = _get_environ(environ)
     return self.description
Esempio n. 30
0
 def get_description(self, environ):
     """Get the description."""
     environ = _get_environ(environ)
     return '<p>%s</p>' % escape(self.description)