Python tornado.web.RequestHandler() Examples

The following are 30 code examples of tornado.web.RequestHandler(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module tornado.web , or try the search function .
Example #1
Source File: web.py    From viewfinder with Apache License 2.0 6 votes vote down vote up
def authenticated(method):
    """Decorate methods with this to require that the user be logged in.

    If the user is not logged in, they will be redirected to the configured
    `login url <RequestHandler.get_login_url>`.
    """
    @functools.wraps(method)
    def wrapper(self, *args, **kwargs):
        if not self.current_user:
            if self.request.method in ("GET", "HEAD"):
                url = self.get_login_url()
                if "?" not in url:
                    if urlparse.urlsplit(url).scheme:
                        # if login url is absolute, make next absolute too
                        next_url = self.request.full_url()
                    else:
                        next_url = self.request.uri
                    url += "?" + urlencode(dict(next=next_url))
                self.redirect(url)
                return
            raise HTTPError(403)
        return method(self, *args, **kwargs)
    return wrapper 
Example #2
Source File: web.py    From viewfinder with Apache License 2.0 6 votes vote down vote up
def get_arguments(self, name, strip=True):
        """Returns a list of the arguments with the given name.

        If the argument is not present, returns an empty list.

        The returned values are always unicode.
        """

        values = []
        for v in self.request.arguments.get(name, []):
            v = self.decode_argument(v, name=name)
            if isinstance(v, unicode_type):
                # Get rid of any weird control chars (unless decoding gave
                # us bytes, in which case leave it alone)
                v = RequestHandler._remove_control_chars_regex.sub(" ", v)
            if strip:
                v = v.strip()
            values.append(v)
        return values 
Example #3
Source File: wsgi_test.py    From viewfinder with Apache License 2.0 6 votes vote down vote up
def get_app(self):
        class HelloHandler(RequestHandler):
            def get(self):
                self.write("Hello world!")

        class PathQuotingHandler(RequestHandler):
            def get(self, path):
                self.write(path)

        # It would be better to run the wsgiref server implementation in
        # another thread instead of using our own WSGIContainer, but this
        # fits better in our async testing framework and the wsgiref
        # validator should keep us honest
        return WSGIContainer(validator(WSGIApplication([
            ("/", HelloHandler),
            ("/path/(.*)", PathQuotingHandler),
            ("/typecheck", TypeCheckHandler),
        ]))) 
Example #4
Source File: httpserver_test.py    From viewfinder with Apache License 2.0 6 votes vote down vote up
def get_app(self):
        class HelloHandler(RequestHandler):
            def get(self):
                self.finish('Hello world')

        class LargeHandler(RequestHandler):
            def get(self):
                # 512KB should be bigger than the socket buffers so it will
                # be written out in chunks.
                self.write(''.join(chr(i % 256) * 1024 for i in range(512)))

        class FinishOnCloseHandler(RequestHandler):
            @asynchronous
            def get(self):
                self.flush()

            def on_connection_close(self):
                # This is not very realistic, but finishing the request
                # from the close callback has the right timing to mimic
                # some errors seen in the wild.
                self.finish('closed')

        return Application([('/', HelloHandler),
                            ('/large', LargeHandler),
                            ('/finish_on_close', FinishOnCloseHandler)]) 
Example #5
Source File: web.py    From viewfinder with Apache License 2.0 6 votes vote down vote up
def _convert_header_value(self, value):
        if isinstance(value, bytes_type):
            pass
        elif isinstance(value, unicode_type):
            value = value.encode('utf-8')
        elif isinstance(value, numbers.Integral):
            # return immediately since we know the converted value will be safe
            return str(value)
        elif isinstance(value, datetime.datetime):
            return httputil.format_timestamp(value)
        else:
            raise TypeError("Unsupported header value %r" % value)
        # If \n is allowed into the header, it is possible to inject
        # additional headers or split the request. Also cap length to
        # prevent obviously erroneous values.
        if (len(value) > 4000 or
                RequestHandler._INVALID_HEADER_CHAR_RE.search(value)):
            raise ValueError("Unsafe header value %r", value)
        return value 
Example #6
Source File: test_tornado.py    From sentry-python with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_formdata(tornado_testcase, sentry_init, capture_events):
    sentry_init(integrations=[TornadoIntegration()], send_default_pii=True)
    events = capture_events()

    class FormdataHandler(RequestHandler):
        def post(self):
            raise ValueError(json.dumps(sorted(self.request.body_arguments)))

    client = tornado_testcase(Application([(r"/form", FormdataHandler)]))

    response = client.fetch(
        "/form?queryarg=1",
        method="POST",
        headers={"Content-Type": "application/x-www-form-urlencoded"},
        body=b"field1=value1&field2=value2",
    )

    assert response.code == 500

    (event,) = events
    (exception,) = event["exception"]["values"]
    assert exception["value"] == '["field1", "field2"]'
    assert event["request"]["data"] == {"field1": ["value1"], "field2": ["value2"]} 
Example #7
Source File: websocket_test.py    From opendevops with GNU General Public License v3.0 6 votes vote down vote up
def open(self):
        methods_to_test = [
            functools.partial(self.write, "This should not work"),
            functools.partial(self.redirect, "http://localhost/elsewhere"),
            functools.partial(self.set_header, "X-Test", ""),
            functools.partial(self.set_cookie, "Chocolate", "Chip"),
            functools.partial(self.set_status, 503),
            self.flush,
            self.finish,
        ]
        for method in methods_to_test:
            try:
                # In a websocket context, many RequestHandler methods
                # raise RuntimeErrors.
                method()
                raise Exception("did not get expected exception")
            except RuntimeError:
                pass
        self.write_message(self.request.headers.get("X-Test", "")) 
Example #8
Source File: web.py    From viewfinder with Apache License 2.0 6 votes vote down vote up
def _convert_header_value(self, value):
        if isinstance(value, bytes_type):
            pass
        elif isinstance(value, unicode_type):
            value = value.encode('utf-8')
        elif isinstance(value, numbers.Integral):
            # return immediately since we know the converted value will be safe
            return str(value)
        elif isinstance(value, datetime.datetime):
            return httputil.format_timestamp(value)
        else:
            raise TypeError("Unsupported header value %r" % value)
        # If \n is allowed into the header, it is possible to inject
        # additional headers or split the request. Also cap length to
        # prevent obviously erroneous values.
        if (len(value) > 4000 or
                RequestHandler._INVALID_HEADER_CHAR_RE.search(value)):
            raise ValueError("Unsafe header value %r", value)
        return value 
Example #9
Source File: web.py    From viewfinder with Apache License 2.0 6 votes vote down vote up
def get_arguments(self, name, strip=True):
        """Returns a list of the arguments with the given name.

        If the argument is not present, returns an empty list.

        The returned values are always unicode.
        """

        values = []
        for v in self.request.arguments.get(name, []):
            v = self.decode_argument(v, name=name)
            if isinstance(v, unicode_type):
                # Get rid of any weird control chars (unless decoding gave
                # us bytes, in which case leave it alone)
                v = RequestHandler._remove_control_chars_regex.sub(" ", v)
            if strip:
                v = v.strip()
            values.append(v)
        return values 
Example #10
Source File: web.py    From viewfinder with Apache License 2.0 6 votes vote down vote up
def render_string(self, template_name, **kwargs):
        """Generate the given template with the given arguments.

        We return the generated byte string (in utf8). To generate and
        write a template as a response, use render() above.
        """
        # If no template_path is specified, use the path of the calling file
        template_path = self.get_template_path()
        if not template_path:
            frame = sys._getframe(0)
            web_file = frame.f_code.co_filename
            while frame.f_code.co_filename == web_file:
                frame = frame.f_back
            template_path = os.path.dirname(frame.f_code.co_filename)
        with RequestHandler._template_loader_lock:
            if template_path not in RequestHandler._template_loaders:
                loader = self.create_template_loader(template_path)
                RequestHandler._template_loaders[template_path] = loader
            else:
                loader = RequestHandler._template_loaders[template_path]
        t = loader.load(template_name)
        namespace = self.get_template_namespace()
        namespace.update(kwargs)
        return t.generate(**namespace) 
Example #11
Source File: wsgi_test.py    From tornado-zh with MIT License 6 votes vote down vote up
def get_app(self):
        class HelloHandler(RequestHandler):
            def get(self):
                self.write("Hello world!")

        class PathQuotingHandler(RequestHandler):
            def get(self, path):
                self.write(path)

        # It would be better to run the wsgiref server implementation in
        # another thread instead of using our own WSGIContainer, but this
        # fits better in our async testing framework and the wsgiref
        # validator should keep us honest
        return WSGIContainer(validator(WSGIApplication([
            ("/", HelloHandler),
            ("/path/(.*)", PathQuotingHandler),
            ("/typecheck", TypeCheckHandler),
        ]))) 
Example #12
Source File: web.py    From viewfinder with Apache License 2.0 6 votes vote down vote up
def initialize(self):
        """Hook for subclass initialization.

        A dictionary passed as the third argument of a url spec will be
        supplied as keyword arguments to initialize().

        Example::

            class ProfileHandler(RequestHandler):
                def initialize(self, database):
                    self.database = database

                def get(self, username):
                    ...

            app = Application([
                (r'/user/(.*)', ProfileHandler, dict(database=database)),
                ])
        """
        pass 
Example #13
Source File: web.py    From viewfinder with Apache License 2.0 6 votes vote down vote up
def authenticated(method):
    """Decorate methods with this to require that the user be logged in.

    If the user is not logged in, they will be redirected to the configured
    `login url <RequestHandler.get_login_url>`.
    """
    @functools.wraps(method)
    def wrapper(self, *args, **kwargs):
        if not self.current_user:
            if self.request.method in ("GET", "HEAD"):
                url = self.get_login_url()
                if "?" not in url:
                    if urlparse.urlsplit(url).scheme:
                        # if login url is absolute, make next absolute too
                        next_url = self.request.full_url()
                    else:
                        next_url = self.request.uri
                    url += "?" + urlencode(dict(next=next_url))
                self.redirect(url)
                return
            raise HTTPError(403)
        return method(self, *args, **kwargs)
    return wrapper 
Example #14
Source File: web.py    From viewfinder with Apache License 2.0 6 votes vote down vote up
def __init__(self, pattern, handler_class, kwargs=None, name=None):
        """Parameters:

        * ``pattern``: Regular expression to be matched.  Any groups
          in the regex will be passed in to the handler's get/post/etc
          methods as arguments.

        * ``handler_class``: `RequestHandler` subclass to be invoked.

        * ``kwargs`` (optional): A dictionary of additional arguments
          to be passed to the handler's constructor.

        * ``name`` (optional): A name for this handler.  Used by
          `Application.reverse_url`.
        """
        if not pattern.endswith('$'):
            pattern += '$'
        self.regex = re.compile(pattern)
        assert len(self.regex.groupindex) in (0, self.regex.groups), \
            ("groups in url regexes must either be all named or all "
             "positional: %r" % self.regex.pattern)
        self.handler_class = handler_class
        self.kwargs = kwargs or {}
        self.name = name
        self._path, self._group_count = self._find_groups() 
Example #15
Source File: routing_test.py    From opendevops with GNU General Public License v3.0 6 votes vote down vote up
def get_app(self):
        wsgi_app = WSGIContainer(self.wsgi_app)

        class Handler(RequestHandler):
            def get(self, *args, **kwargs):
                self.finish(self.reverse_url("tornado"))

        return RuleRouter(
            [
                (
                    PathMatches("/tornado.*"),
                    Application([(r"/tornado/test", Handler, {}, "tornado")]),
                ),
                (PathMatches("/wsgi"), wsgi_app),
            ]
        ) 
Example #16
Source File: httpserver_test.py    From viewfinder with Apache License 2.0 6 votes vote down vote up
def get_app(self):
        class HelloHandler(RequestHandler):
            def get(self):
                self.finish('Hello world')

        class LargeHandler(RequestHandler):
            def get(self):
                # 512KB should be bigger than the socket buffers so it will
                # be written out in chunks.
                self.write(''.join(chr(i % 256) * 1024 for i in range(512)))

        class FinishOnCloseHandler(RequestHandler):
            @asynchronous
            def get(self):
                self.flush()

            def on_connection_close(self):
                # This is not very realistic, but finishing the request
                # from the close callback has the right timing to mimic
                # some errors seen in the wild.
                self.finish('closed')

        return Application([('/', HelloHandler),
                            ('/large', LargeHandler),
                            ('/finish_on_close', FinishOnCloseHandler)]) 
Example #17
Source File: web.py    From viewfinder with Apache License 2.0 6 votes vote down vote up
def render_string(self, template_name, **kwargs):
        """Generate the given template with the given arguments.

        We return the generated byte string (in utf8). To generate and
        write a template as a response, use render() above.
        """
        # If no template_path is specified, use the path of the calling file
        template_path = self.get_template_path()
        if not template_path:
            frame = sys._getframe(0)
            web_file = frame.f_code.co_filename
            while frame.f_code.co_filename == web_file:
                frame = frame.f_back
            template_path = os.path.dirname(frame.f_code.co_filename)
        with RequestHandler._template_loader_lock:
            if template_path not in RequestHandler._template_loaders:
                loader = self.create_template_loader(template_path)
                RequestHandler._template_loaders[template_path] = loader
            else:
                loader = RequestHandler._template_loaders[template_path]
        t = loader.load(template_name)
        namespace = self.get_template_namespace()
        namespace.update(kwargs)
        return t.generate(**namespace) 
Example #18
Source File: test_ext_tornado.py    From apispec-webframeworks with MIT License 6 votes vote down vote up
def test_path_with_multiple_methods(self, spec):
        class HelloHandler(RequestHandler):
            def get(self):
                self.write("hello")

            def post(self):
                self.write("hello")

        urlspec = (r"/hello", HelloHandler)
        operations = {
            "get": {"description": "get a greeting", "responses": {"200": {}}},
            "post": {"description": "post a greeting", "responses": {"200": {}}},
        }
        spec.path(urlspec=urlspec, operations=operations)
        paths = get_paths(spec)
        get_op = paths["/hello"]["get"]
        post_op = paths["/hello"]["post"]
        assert get_op["description"] == "get a greeting"
        assert post_op["description"] == "post a greeting" 
Example #19
Source File: wsgi_test.py    From tornado-zh with MIT License 6 votes vote down vote up
def get_app(self):
        class HelloHandler(RequestHandler):
            def get(self):
                self.write("Hello world!")

        class PathQuotingHandler(RequestHandler):
            def get(self, path):
                self.write(path)

        # It would be better to run the wsgiref server implementation in
        # another thread instead of using our own WSGIContainer, but this
        # fits better in our async testing framework and the wsgiref
        # validator should keep us honest
        return WSGIContainer(validator(WSGIApplication([
            ("/", HelloHandler),
            ("/path/(.*)", PathQuotingHandler),
            ("/typecheck", TypeCheckHandler),
        ]))) 
Example #20
Source File: auth.py    From opendevops with GNU General Public License v3.0 6 votes vote down vote up
def _on_request_token(
        self,
        authorize_url: str,
        callback_uri: Optional[str],
        response: httpclient.HTTPResponse,
    ) -> None:
        handler = cast(RequestHandler, self)
        request_token = _oauth_parse_response(response.body)
        data = (
            base64.b64encode(escape.utf8(request_token["key"]))
            + b"|"
            + base64.b64encode(escape.utf8(request_token["secret"]))
        )
        handler.set_cookie("_oauth_request_token", data)
        args = dict(oauth_token=request_token["key"])
        if callback_uri == "oob":
            handler.finish(authorize_url + "?" + urllib.parse.urlencode(args))
            return
        elif callback_uri:
            args["oauth_callback"] = urllib.parse.urljoin(
                handler.request.full_url(), callback_uri
            )
        handler.redirect(authorize_url + "?" + urllib.parse.urlencode(args)) 
Example #21
Source File: test_swirl.py    From tornado-swirl with MIT License 5 votes vote down vote up
def test_request_body_form_data(self):
        self.reset_settings()
        @swirl.restapi(r'/test/form')
        class HandlerTest(RequestHandler):
            def post(self, a, b):
                """This is a simple test post with form data.

                This is a simple description.

                Request Body:
                    a (string) -- The a.
                    b (integer) -- The b

                Response:
                    out (string) -- An output.

                Errors:
                    400 -- Bad Request
                    404 -- Not Found
                """
                self.finish()

        self.get_app().add_handlers(r".*", api_routes())
        response = yield self.http_client.fetch(self.get_url('/swagger/spec'))
        obj = json.loads(response.body.decode('utf-8'))
        assert obj['paths']
        assert obj['paths']['/test/form']
        assert obj['paths']['/test/form']['post']
        assert obj['paths']['/test/form']['post']['requestBody']
        assert obj['paths']['/test/form']['post']['requestBody']['content']
        assert obj['paths']['/test/form']['post']['requestBody']['content']['application/x-www-form-urlencoded'] 
Example #22
Source File: test_swirl.py    From tornado-swirl with MIT License 5 votes vote down vote up
def test_simple_1(self):
        self.reset_settings()
        @swirl.restapi('/test')
        class HandlerTest(RequestHandler):
            def get(self):
                """This is a simple test get.

                This is a simple description.

                Query Parameters:
                    foo (string) -- Optional. Simple query string.

                Response:
                    out (string) -- An output.
                """
                self.finish()

        self._app.add_handlers(r".*", api_routes())
        response = yield self.http_client.fetch(self.get_url('/swagger/spec'))
        obj = json.loads(response.body.decode('utf-8'))
        assert obj['paths']
        assert obj['paths']['/test']
        assert obj['paths']['/test']['get']

        obj = obj['paths']['/test']['get']
        assert obj['responses']
        assert obj['responses']['200']
        assert obj['responses']['200']['description'] == 'An output.'
        assert obj['responses']['200']['content']['text/plain']['schema']
        assert obj['responses']['200']['content']['text/plain']['schema']['type'] == 'string' 
Example #23
Source File: test_swirl.py    From tornado-swirl with MIT License 5 votes vote down vote up
def test_simple_2(self):
        self.reset_settings()
        @swirl.restapi(r'/test/(?P<a>\w+)/(?P<b>\d+)')
        class HandlerTest(RequestHandler):
            def post(self, a, b):
                """This is a simple test get.

                This is a simple description.

                Path Parameters:
                    a (string) -- The a.
                    b (integer) -- The b

                Response:
                    out (string) -- An output.

                Errors:
                    400 -- Bad Request
                    404 -- Not Found
                """
                self.finish()

        self.get_app().add_handlers(r".*", api_routes())
        response = yield self.http_client.fetch(self.get_url('/swagger/spec'))
        obj = json.loads(response.body.decode('utf-8'))

        assert obj['paths']
        assert obj['paths']['/test/{a}/{b}']
        assert obj['paths']['/test/{a}/{b}']['post']

        obj = obj['paths']['/test/{a}/{b}']['post']
        assert obj['responses']['400']
        assert obj['responses']['404'] 
Example #24
Source File: twisted_test.py    From viewfinder with Apache License 2.0 5 votes vote down vote up
def start_tornado_server(self):
        class HelloHandler(RequestHandler):
            def get(self):
                self.write("Hello from tornado!")
        app = Application([('/', HelloHandler)],
                          log_function=lambda x: None)
        server = HTTPServer(app, io_loop=self.io_loop)
        sock, self.tornado_port = bind_unused_port()
        server.add_sockets([sock]) 
Example #25
Source File: web.py    From viewfinder with Apache License 2.0 5 votes vote down vote up
def __init__(self, application, request, **kwargs):
        super(RequestHandler, self).__init__()

        self.application = application
        self.request = request
        self._headers_written = False
        self._finished = False
        self._auto_finish = True
        self._transforms = None  # will be set in _execute
        self.path_args = None
        self.path_kwargs = None
        self.ui = ObjectDict((n, self._ui_method(m)) for n, m in
                             application.ui_methods.items())
        # UIModules are available as both `modules` and `_tt_modules` in the
        # template namespace.  Historically only `modules` was available
        # but could be clobbered by user additions to the namespace.
        # The template {% module %} directive looks in `_tt_modules` to avoid
        # possible conflicts.
        self.ui["_tt_modules"] = _UIModuleNamespace(self,
                                                    application.ui_modules)
        self.ui["modules"] = self.ui["_tt_modules"]
        self.clear()
        # Check since connection is not available in WSGI
        if getattr(self.request, "connection", None):
            self.request.connection.set_close_callback(
                self.on_connection_close)
        self.initialize(**kwargs) 
Example #26
Source File: test_ext_tornado.py    From apispec-webframeworks with MIT License 5 votes vote down vote up
def test_integration_with_docstring_introspection(self, spec):
        class HelloHandler(RequestHandler):
            """
            ---
            x-extension: value
            """

            def get(self):
                """Get a greeting endpoint.
                ---
                description: get a greeting
                responses:
                    200:
                        description: a pet to be returned
                        schema:
                            $ref: #/definitions/Pet
                """
                self.write("hello")

            def post(self):
                """Post a greeting endpoint.
                ---
                description: post a greeting
                responses:
                    200:
                        description: some data
                """
                self.write("hello")

        urlspec = (r"/hello", HelloHandler)
        spec.path(urlspec=urlspec)
        paths = get_paths(spec)
        get_op = paths["/hello"]["get"]
        post_op = paths["/hello"]["post"]
        extension = paths["/hello"]["x-extension"]
        assert get_op["description"] == "get a greeting"
        assert post_op["description"] == "post a greeting"
        assert extension == "value" 
Example #27
Source File: test_ext_tornado.py    From apispec-webframeworks with MIT License 5 votes vote down vote up
def test_path_from_urlspec(self, spec):
        class HelloHandler(RequestHandler):
            def get(self):
                self.write("hello")

        urlspec = (r"/hello", HelloHandler)
        operations = {"get": {"parameters": [], "responses": {"200": {}}}}

        spec.path(urlspec=urlspec, operations=operations)
        paths = get_paths(spec)
        assert "/hello" in paths
        assert "get" in paths["/hello"]
        expected = {"parameters": [], "responses": {"200": {}}}
        assert paths["/hello"]["get"] == expected 
Example #28
Source File: tornado.py    From apispec-webframeworks with MIT License 5 votes vote down vote up
def _extensions_from_handler(handler_class):
        """Returns extensions dict from handler docstring

        :param handler_class:
        :type handler_class: RequestHandler descendant
        """
        return yaml_utils.load_yaml_from_docstring(handler_class.__doc__) 
Example #29
Source File: tornado.py    From apispec-webframeworks with MIT License 5 votes vote down vote up
def _operations_from_methods(handler_class):
        """Generator of operations described in handler's http methods

        :param handler_class:
        :type handler_class: RequestHandler descendant
        """
        for httpmethod in yaml_utils.PATH_KEYS:
            method = getattr(handler_class, httpmethod)
            operation_data = yaml_utils.load_yaml_from_docstring(method.__doc__)
            if operation_data:
                operation = {httpmethod: operation_data}
                yield operation 
Example #30
Source File: handlers.py    From Computable with MIT License 5 votes vote down vote up
def render(*args, **kwargs):
        kwargs.setdefault('message', '')
        return web.RequestHandler.render(*args, **kwargs)