{
    "file_diffs": [
        {
            "old_file_content": "from __future__ import absolute_import, division, print_function, with_statement\nfrom tornado import gen\nfrom tornado.escape import json_decode, utf8, to_unicode, recursive_unicode, native_str, to_basestring\nfrom tornado.httputil import format_timestamp\nfrom tornado.iostream import IOStream\nfrom tornado.log import app_log, gen_log\nfrom tornado.simple_httpclient import SimpleAsyncHTTPClient\nfrom tornado.template import DictLoader\nfrom tornado.testing import AsyncHTTPTestCase, ExpectLog\nfrom tornado.test.util import unittest\nfrom tornado.util import u, bytes_type, ObjectDict, unicode_type\nfrom tornado.web import RequestHandler, authenticated, Application, asynchronous, url, HTTPError, StaticFileHandler, _create_signature, create_signed_value, ErrorHandler, UIModule, MissingArgumentError\n\nimport binascii\nimport datetime\nimport email.utils\nimport logging\nimport os\nimport re\nimport socket\nimport sys\n\nwsgi_safe_tests = []\n\nrelpath = lambda *a: os.path.join(os.path.dirname(__file__), *a)\n\n\ndef wsgi_safe(cls):\n    wsgi_safe_tests.append(cls)\n    return cls\n\n\nclass WebTestCase(AsyncHTTPTestCase):\n    \"\"\"Base class for web tests that also supports WSGI mode.\n\n    Override get_handlers and get_app_kwargs instead of get_app.\n    Append to wsgi_safe to have it run in wsgi_test as well.\n    \"\"\"\n    def get_app(self):\n        self.app = Application(self.get_handlers(), **self.get_app_kwargs())\n        return self.app\n\n    def get_handlers(self):\n        raise NotImplementedError()\n\n    def get_app_kwargs(self):\n        return {}\n\n\nclass SimpleHandlerTestCase(WebTestCase):\n    \"\"\"Simplified base class for tests that work with a single handler class.\n\n    To use, define a nested class named ``Handler``.\n    \"\"\"\n    def get_handlers(self):\n        return [('/', self.Handler)]\n\n\nclass CookieTestRequestHandler(RequestHandler):\n    # stub out enough methods to make the secure_cookie functions work\n    def __init__(self):\n        # don't call super.__init__\n        self._cookies = {}\n        self.application = ObjectDict(settings=dict(cookie_secret='0123456789'))\n\n    def get_cookie(self, name):\n        return self._cookies.get(name)\n\n    def set_cookie(self, name, value, expires_days=None):\n        self._cookies[name] = value\n\n\nclass SecureCookieTest(unittest.TestCase):\n    def test_round_trip(self):\n        handler = CookieTestRequestHandler()\n        handler.set_secure_cookie('foo', b'bar')\n        self.assertEqual(handler.get_secure_cookie('foo'), b'bar')\n\n    def test_cookie_tampering_future_timestamp(self):\n        handler = CookieTestRequestHandler()\n        # this string base64-encodes to '12345678'\n        handler.set_secure_cookie('foo', binascii.a2b_hex(b'd76df8e7aefc'))\n        cookie = handler._cookies['foo']\n        match = re.match(br'12345678\\|([0-9]+)\\|([0-9a-f]+)', cookie)\n        self.assertTrue(match)\n        timestamp = match.group(1)\n        sig = match.group(2)\n        self.assertEqual(\n            _create_signature(handler.application.settings[\"cookie_secret\"],\n                              'foo', '12345678', timestamp),\n            sig)\n        # shifting digits from payload to timestamp doesn't alter signature\n        # (this is not desirable behavior, just confirming that that's how it\n        # works)\n        self.assertEqual(\n            _create_signature(handler.application.settings[\"cookie_secret\"],\n                              'foo', '1234', b'5678' + timestamp),\n            sig)\n        # tamper with the cookie\n        handler._cookies['foo'] = utf8('1234|5678%s|%s' % (\n            to_basestring(timestamp), to_basestring(sig)))\n        # it gets rejected\n        with ExpectLog(gen_log, \"Cookie timestamp in future\"):\n            self.assertTrue(handler.get_secure_cookie('foo') is None)\n\n    def test_arbitrary_bytes(self):\n        # Secure cookies accept arbitrary data (which is base64 encoded).\n        # Note that normal cookies accept only a subset of ascii.\n        handler = CookieTestRequestHandler()\n        handler.set_secure_cookie('foo', b'\\xe9')\n        self.assertEqual(handler.get_secure_cookie('foo'), b'\\xe9')\n\n\nclass CookieTest(WebTestCase):\n    def get_handlers(self):\n        class SetCookieHandler(RequestHandler):\n            def get(self):\n                # Try setting cookies with different argument types\n                # to ensure that everything gets encoded correctly\n                self.set_cookie(\"str\", \"asdf\")\n                self.set_cookie(\"unicode\", u(\"qwer\"))\n                self.set_cookie(\"bytes\", b\"zxcv\")\n\n        class GetCookieHandler(RequestHandler):\n            def get(self):\n                self.write(self.get_cookie(\"foo\", \"default\"))\n\n        class SetCookieDomainHandler(RequestHandler):\n            def get(self):\n                # unicode domain and path arguments shouldn't break things\n                # either (see bug #285)\n                self.set_cookie(\"unicode_args\", \"blah\", domain=u(\"foo.com\"),\n                                path=u(\"/foo\"))\n\n        class SetCookieSpecialCharHandler(RequestHandler):\n            def get(self):\n                self.set_cookie(\"equals\", \"a=b\")\n                self.set_cookie(\"semicolon\", \"a;b\")\n                self.set_cookie(\"quote\", 'a\"b')\n\n        class SetCookieOverwriteHandler(RequestHandler):\n            def get(self):\n                self.set_cookie(\"a\", \"b\", domain=\"example.com\")\n                self.set_cookie(\"c\", \"d\", domain=\"example.com\")\n                # A second call with the same name clobbers the first.\n                # Attributes from the first call are not carried over.\n                self.set_cookie(\"a\", \"e\")\n\n        return [(\"/set\", SetCookieHandler),\n                (\"/get\", GetCookieHandler),\n                (\"/set_domain\", SetCookieDomainHandler),\n                (\"/special_char\", SetCookieSpecialCharHandler),\n                (\"/set_overwrite\", SetCookieOverwriteHandler),\n                ]\n\n    def test_set_cookie(self):\n        response = self.fetch(\"/set\")\n        self.assertEqual(sorted(response.headers.get_list(\"Set-Cookie\")),\n                         [\"bytes=zxcv; Path=/\",\n                          \"str=asdf; Path=/\",\n                          \"unicode=qwer; Path=/\",\n                          ])\n\n    def test_get_cookie(self):\n        response = self.fetch(\"/get\", headers={\"Cookie\": \"foo=bar\"})\n        self.assertEqual(response.body, b\"bar\")\n\n        response = self.fetch(\"/get\", headers={\"Cookie\": 'foo=\"bar\"'})\n        self.assertEqual(response.body, b\"bar\")\n\n        response = self.fetch(\"/get\", headers={\"Cookie\": \"/=exception;\"})\n        self.assertEqual(response.body, b\"default\")\n\n    def test_set_cookie_domain(self):\n        response = self.fetch(\"/set_domain\")\n        self.assertEqual(response.headers.get_list(\"Set-Cookie\"),\n                         [\"unicode_args=blah; Domain=foo.com; Path=/foo\"])\n\n    def test_cookie_special_char(self):\n        response = self.fetch(\"/special_char\")\n        headers = sorted(response.headers.get_list(\"Set-Cookie\"))\n        self.assertEqual(len(headers), 3)\n        self.assertEqual(headers[0], 'equals=\"a=b\"; Path=/')\n        self.assertEqual(headers[1], 'quote=\"a\\\\\"b\"; Path=/')\n        # python 2.7 octal-escapes the semicolon; older versions leave it alone\n        self.assertTrue(headers[2] in ('semicolon=\"a;b\"; Path=/',\n                                       'semicolon=\"a\\\\073b\"; Path=/'),\n                        headers[2])\n\n        data = [('foo=a=b', 'a=b'),\n                ('foo=\"a=b\"', 'a=b'),\n                ('foo=\"a;b\"', 'a;b'),\n                # ('foo=a\\\\073b', 'a;b'),  # even encoded, \";\" is a delimiter\n                ('foo=\"a\\\\073b\"', 'a;b'),\n                ('foo=\"a\\\\\"b\"', 'a\"b'),\n                ]\n        for header, expected in data:\n            logging.debug(\"trying %r\", header)\n            response = self.fetch(\"/get\", headers={\"Cookie\": header})\n            self.assertEqual(response.body, utf8(expected))\n\n    def test_set_cookie_overwrite(self):\n        response = self.fetch(\"/set_overwrite\")\n        headers = response.headers.get_list(\"Set-Cookie\")\n        self.assertEqual(sorted(headers),\n                         [\"a=e; Path=/\", \"c=d; Domain=example.com; Path=/\"])\n\n\nclass AuthRedirectRequestHandler(RequestHandler):\n    def initialize(self, login_url):\n        self.login_url = login_url\n\n    def get_login_url(self):\n        return self.login_url\n\n    @authenticated\n    def get(self):\n        # we'll never actually get here because the test doesn't follow redirects\n        self.send_error(500)\n\n\nclass AuthRedirectTest(WebTestCase):\n    def get_handlers(self):\n        return [('/relative', AuthRedirectRequestHandler,\n                 dict(login_url='/login')),\n                ('/absolute', AuthRedirectRequestHandler,\n                 dict(login_url='http://example.com/login'))]\n\n    def test_relative_auth_redirect(self):\n        self.http_client.fetch(self.get_url('/relative'), self.stop,\n                               follow_redirects=False)\n        response = self.wait()\n        self.assertEqual(response.code, 302)\n        self.assertEqual(response.headers['Location'], '/login?next=%2Frelative')\n\n    def test_absolute_auth_redirect(self):\n        self.http_client.fetch(self.get_url('/absolute'), self.stop,\n                               follow_redirects=False)\n        response = self.wait()\n        self.assertEqual(response.code, 302)\n        self.assertTrue(re.match(\n            'http://example.com/login\\?next=http%3A%2F%2Flocalhost%3A[0-9]+%2Fabsolute',\n            response.headers['Location']), response.headers['Location'])\n\n\nclass ConnectionCloseHandler(RequestHandler):\n    def initialize(self, test):\n        self.test = test\n\n    @asynchronous\n    def get(self):\n        self.test.on_handler_waiting()\n\n    def on_connection_close(self):\n        self.test.on_connection_close()\n\n\nclass ConnectionCloseTest(WebTestCase):\n    def get_handlers(self):\n        return [('/', ConnectionCloseHandler, dict(test=self))]\n\n    def test_connection_close(self):\n        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)\n        s.connect((\"localhost\", self.get_http_port()))\n        self.stream = IOStream(s, io_loop=self.io_loop)\n        self.stream.write(b\"GET / HTTP/1.0\\r\\n\\r\\n\")\n        self.wait()\n\n    def on_handler_waiting(self):\n        logging.debug('handler waiting')\n        self.stream.close()\n\n    def on_connection_close(self):\n        logging.debug('connection closed')\n        self.stop()\n\n\nclass EchoHandler(RequestHandler):\n    def get(self, *path_args):\n        # Type checks: web.py interfaces convert argument values to\n        # unicode strings (by default, but see also decode_argument).\n        # In httpserver.py (i.e. self.request.arguments), they're left\n        # as bytes.  Keys are always native strings.\n        for key in self.request.arguments:\n            if type(key) != str:\n                raise Exception(\"incorrect type for key: %r\" % type(key))\n            for value in self.request.arguments[key]:\n                if type(value) != bytes_type:\n                    raise Exception(\"incorrect type for value: %r\" %\n                                    type(value))\n            for value in self.get_arguments(key):\n                if type(value) != unicode_type:\n                    raise Exception(\"incorrect type for value: %r\" %\n                                    type(value))\n        for arg in path_args:\n            if type(arg) != unicode_type:\n                raise Exception(\"incorrect type for path arg: %r\" % type(arg))\n        self.write(dict(path=self.request.path,\n                        path_args=path_args,\n                        args=recursive_unicode(self.request.arguments)))\n\n\nclass RequestEncodingTest(WebTestCase):\n    def get_handlers(self):\n        return [(\"/group/(.*)\", EchoHandler),\n                (\"/slashes/([^/]*)/([^/]*)\", EchoHandler),\n                ]\n\n    def fetch_json(self, path):\n        return json_decode(self.fetch(path).body)\n\n    def test_group_question_mark(self):\n        # Ensure that url-encoded question marks are handled properly\n        self.assertEqual(self.fetch_json('/group/%3F'),\n                         dict(path='/group/%3F', path_args=['?'], args={}))\n        self.assertEqual(self.fetch_json('/group/%3F?%3F=%3F'),\n                         dict(path='/group/%3F', path_args=['?'], args={'?': ['?']}))\n\n    def test_group_encoding(self):\n        # Path components and query arguments should be decoded the same way\n        self.assertEqual(self.fetch_json('/group/%C3%A9?arg=%C3%A9'),\n                         {u(\"path\"): u(\"/group/%C3%A9\"),\n                          u(\"path_args\"): [u(\"\\u00e9\")],\n                          u(\"args\"): {u(\"arg\"): [u(\"\\u00e9\")]}})\n\n    def test_slashes(self):\n        # Slashes may be escaped to appear as a single \"directory\" in the path,\n        # but they are then unescaped when passed to the get() method.\n        self.assertEqual(self.fetch_json('/slashes/foo/bar'),\n                         dict(path=\"/slashes/foo/bar\",\n                              path_args=[\"foo\", \"bar\"],\n                              args={}))\n        self.assertEqual(self.fetch_json('/slashes/a%2Fb/c%2Fd'),\n                         dict(path=\"/slashes/a%2Fb/c%2Fd\",\n                              path_args=[\"a/b\", \"c/d\"],\n                              args={}))\n\n\nclass TypeCheckHandler(RequestHandler):\n    def prepare(self):\n        self.errors = {}\n\n        self.check_type('status', self.get_status(), int)\n\n        # get_argument is an exception from the general rule of using\n        # type str for non-body data mainly for historical reasons.\n        self.check_type('argument', self.get_argument('foo'), unicode_type)\n        self.check_type('cookie_key', list(self.cookies.keys())[0], str)\n        self.check_type('cookie_value', list(self.cookies.values())[0].value, str)\n\n        # Secure cookies return bytes because they can contain arbitrary\n        # data, but regular cookies are native strings.\n        if list(self.cookies.keys()) != ['asdf']:\n            raise Exception(\"unexpected values for cookie keys: %r\" %\n                            self.cookies.keys())\n        self.check_type('get_secure_cookie', self.get_secure_cookie('asdf'), bytes_type)\n        self.check_type('get_cookie', self.get_cookie('asdf'), str)\n\n        self.check_type('xsrf_token', self.xsrf_token, bytes_type)\n        self.check_type('xsrf_form_html', self.xsrf_form_html(), str)\n\n        self.check_type('reverse_url', self.reverse_url('typecheck', 'foo'), str)\n\n        self.check_type('request_summary', self._request_summary(), str)\n\n    def get(self, path_component):\n        # path_component uses type unicode instead of str for consistency\n        # with get_argument()\n        self.check_type('path_component', path_component, unicode_type)\n        self.write(self.errors)\n\n    def post(self, path_component):\n        self.check_type('path_component', path_component, unicode_type)\n        self.write(self.errors)\n\n    def check_type(self, name, obj, expected_type):\n        actual_type = type(obj)\n        if expected_type != actual_type:\n            self.errors[name] = \"expected %s, got %s\" % (expected_type,\n                                                         actual_type)\n\n\nclass DecodeArgHandler(RequestHandler):\n    def decode_argument(self, value, name=None):\n        if type(value) != bytes_type:\n            raise Exception(\"unexpected type for value: %r\" % type(value))\n        # use self.request.arguments directly to avoid recursion\n        if 'encoding' in self.request.arguments:\n            return value.decode(to_unicode(self.request.arguments['encoding'][0]))\n        else:\n            return value\n\n    def get(self, arg):\n        def describe(s):\n            if type(s) == bytes_type:\n                return [\"bytes\", native_str(binascii.b2a_hex(s))]\n            elif type(s) == unicode_type:\n                return [\"unicode\", s]\n            raise Exception(\"unknown type\")\n        self.write({'path': describe(arg),\n                    'query': describe(self.get_argument(\"foo\")),\n                    })\n\n\nclass LinkifyHandler(RequestHandler):\n    def get(self):\n        self.render(\"linkify.html\", message=\"http://example.com\")\n\n\nclass UIModuleResourceHandler(RequestHandler):\n    def get(self):\n        self.render(\"page.html\", entries=[1, 2])\n\n\nclass OptionalPathHandler(RequestHandler):\n    def get(self, path):\n        self.write({\"path\": path})\n\n\nclass FlowControlHandler(RequestHandler):\n    # These writes are too small to demonstrate real flow control,\n    # but at least it shows that the callbacks get run.\n    @asynchronous\n    def get(self):\n        self.write(\"1\")\n        self.flush(callback=self.step2)\n\n    def step2(self):\n        self.write(\"2\")\n        self.flush(callback=self.step3)\n\n    def step3(self):\n        self.write(\"3\")\n        self.finish()\n\n\nclass MultiHeaderHandler(RequestHandler):\n    def get(self):\n        self.set_header(\"x-overwrite\", \"1\")\n        self.set_header(\"X-Overwrite\", 2)\n        self.add_header(\"x-multi\", 3)\n        self.add_header(\"X-Multi\", \"4\")\n\n\nclass RedirectHandler(RequestHandler):\n    def get(self):\n        if self.get_argument('permanent', None) is not None:\n            self.redirect('/', permanent=int(self.get_argument('permanent')))\n        elif self.get_argument('status', None) is not None:\n            self.redirect('/', status=int(self.get_argument('status')))\n        else:\n            raise Exception(\"didn't get permanent or status arguments\")\n\n\nclass EmptyFlushCallbackHandler(RequestHandler):\n    @gen.engine\n    @asynchronous\n    def get(self):\n        # Ensure that the flush callback is run whether or not there\n        # was any output.\n        yield gen.Task(self.flush)  # \"empty\" flush, but writes headers\n        yield gen.Task(self.flush)  # empty flush\n        self.write(\"o\")\n        yield gen.Task(self.flush)  # flushes the \"o\"\n        yield gen.Task(self.flush)  # empty flush\n        self.finish(\"k\")\n\n\nclass HeaderInjectionHandler(RequestHandler):\n    def get(self):\n        try:\n            self.set_header(\"X-Foo\", \"foo\\r\\nX-Bar: baz\")\n            raise Exception(\"Didn't get expected exception\")\n        except ValueError as e:\n            if \"Unsafe header value\" in str(e):\n                self.finish(b\"ok\")\n            else:\n                raise\n\n\nclass GetArgumentHandler(RequestHandler):\n    def get(self):\n        self.write(self.get_argument(\"foo\", \"default\"))\n\n\n# This test is shared with wsgi_test.py\n@wsgi_safe\nclass WSGISafeWebTest(WebTestCase):\n    COOKIE_SECRET = \"WebTest.COOKIE_SECRET\"\n\n    def get_app_kwargs(self):\n        loader = DictLoader({\n            \"linkify.html\": \"{% module linkify(message) %}\",\n            \"page.html\": \"\"\"\\\n<html><head></head><body>\n{% for e in entries %}\n{% module Template(\"entry.html\", entry=e) %}\n{% end %}\n</body></html>\"\"\",\n            \"entry.html\": \"\"\"\\\n{{ set_resources(embedded_css=\".entry { margin-bottom: 1em; }\", embedded_javascript=\"js_embed()\", css_files=[\"/base.css\", \"/foo.css\"], javascript_files=\"/common.js\", html_head=\"<meta>\", html_body='<script src=\"/analytics.js\"/>') }}\n<div class=\"entry\">...</div>\"\"\",\n        })\n        return dict(template_loader=loader,\n                    autoescape=\"xhtml_escape\",\n                    cookie_secret=self.COOKIE_SECRET)\n\n    def tearDown(self):\n        super(WSGISafeWebTest, self).tearDown()\n        RequestHandler._template_loaders.clear()\n\n    def get_handlers(self):\n        urls = [\n            url(\"/typecheck/(.*)\", TypeCheckHandler, name='typecheck'),\n            url(\"/decode_arg/(.*)\", DecodeArgHandler, name='decode_arg'),\n            url(\"/decode_arg_kw/(?P<arg>.*)\", DecodeArgHandler),\n            url(\"/linkify\", LinkifyHandler),\n            url(\"/uimodule_resources\", UIModuleResourceHandler),\n            url(\"/optional_path/(.+)?\", OptionalPathHandler),\n            url(\"/multi_header\", MultiHeaderHandler),\n            url(\"/redirect\", RedirectHandler),\n            url(\"/header_injection\", HeaderInjectionHandler),\n            url(\"/get_argument\", GetArgumentHandler),\n        ]\n        return urls\n\n    def fetch_json(self, *args, **kwargs):\n        response = self.fetch(*args, **kwargs)\n        response.rethrow()\n        return json_decode(response.body)\n\n    def test_types(self):\n        cookie_value = to_unicode(create_signed_value(self.COOKIE_SECRET,\n                                                      \"asdf\", \"qwer\"))\n        response = self.fetch(\"/typecheck/asdf?foo=bar\",\n                              headers={\"Cookie\": \"asdf=\" + cookie_value})\n        data = json_decode(response.body)\n        self.assertEqual(data, {})\n\n        response = self.fetch(\"/typecheck/asdf?foo=bar\", method=\"POST\",\n                              headers={\"Cookie\": \"asdf=\" + cookie_value},\n                              body=\"foo=bar\")\n\n    def test_decode_argument(self):\n        # These urls all decode to the same thing\n        urls = [\"/decode_arg/%C3%A9?foo=%C3%A9&encoding=utf-8\",\n                \"/decode_arg/%E9?foo=%E9&encoding=latin1\",\n                \"/decode_arg_kw/%E9?foo=%E9&encoding=latin1\",\n                ]\n        for url in urls:\n            response = self.fetch(url)\n            response.rethrow()\n            data = json_decode(response.body)\n            self.assertEqual(data, {u('path'): [u('unicode'), u('\\u00e9')],\n                                    u('query'): [u('unicode'), u('\\u00e9')],\n                                    })\n\n        response = self.fetch(\"/decode_arg/%C3%A9?foo=%C3%A9\")\n        response.rethrow()\n        data = json_decode(response.body)\n        self.assertEqual(data, {u('path'): [u('bytes'), u('c3a9')],\n                                u('query'): [u('bytes'), u('c3a9')],\n                                })\n\n    def test_decode_argument_plus(self):\n        # These urls are all equivalent.\n        urls = [\"/decode_arg/1%20%2B%201?foo=1%20%2B%201&encoding=utf-8\",\n                \"/decode_arg/1%20+%201?foo=1+%2B+1&encoding=utf-8\"]\n        for url in urls:\n            response = self.fetch(url)\n            response.rethrow()\n            data = json_decode(response.body)\n            self.assertEqual(data, {u('path'): [u('unicode'), u('1 + 1')],\n                                    u('query'): [u('unicode'), u('1 + 1')],\n                                    })\n\n    def test_reverse_url(self):\n        self.assertEqual(self.app.reverse_url('decode_arg', 'foo'),\n                         '/decode_arg/foo')\n        self.assertEqual(self.app.reverse_url('decode_arg', 42),\n                         '/decode_arg/42')\n        self.assertEqual(self.app.reverse_url('decode_arg', b'\\xe9'),\n                         '/decode_arg/%E9')\n        self.assertEqual(self.app.reverse_url('decode_arg', u('\\u00e9')),\n                         '/decode_arg/%C3%A9')\n        self.assertEqual(self.app.reverse_url('decode_arg', '1 + 1'),\n                         '/decode_arg/1%20%2B%201')\n\n    def test_uimodule_unescaped(self):\n        response = self.fetch(\"/linkify\")\n        self.assertEqual(response.body,\n                         b\"<a href=\\\"http://example.com\\\">http://example.com</a>\")\n\n    def test_uimodule_resources(self):\n        response = self.fetch(\"/uimodule_resources\")\n        self.assertEqual(response.body, b\"\"\"\\\n<html><head><link href=\"/base.css\" type=\"text/css\" rel=\"stylesheet\"/><link href=\"/foo.css\" type=\"text/css\" rel=\"stylesheet\"/>\n<style type=\"text/css\">\n.entry { margin-bottom: 1em; }\n</style>\n<meta>\n</head><body>\n\n\n<div class=\"entry\">...</div>\n\n\n<div class=\"entry\">...</div>\n\n<script src=\"/common.js\" type=\"text/javascript\"></script>\n<script type=\"text/javascript\">\n//<![CDATA[\njs_embed()\n//]]>\n</script>\n<script src=\"/analytics.js\"/>\n</body></html>\"\"\")\n\n    def test_optional_path(self):\n        self.assertEqual(self.fetch_json(\"/optional_path/foo\"),\n                         {u(\"path\"): u(\"foo\")})\n        self.assertEqual(self.fetch_json(\"/optional_path/\"),\n                         {u(\"path\"): None})\n\n    def test_multi_header(self):\n        response = self.fetch(\"/multi_header\")\n        self.assertEqual(response.headers[\"x-overwrite\"], \"2\")\n        self.assertEqual(response.headers.get_list(\"x-multi\"), [\"3\", \"4\"])\n\n    def test_redirect(self):\n        response = self.fetch(\"/redirect?permanent=1\", follow_redirects=False)\n        self.assertEqual(response.code, 301)\n        response = self.fetch(\"/redirect?permanent=0\", follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        response = self.fetch(\"/redirect?status=307\", follow_redirects=False)\n        self.assertEqual(response.code, 307)\n\n    def test_header_injection(self):\n        response = self.fetch(\"/header_injection\")\n        self.assertEqual(response.body, b\"ok\")\n\n    def test_get_argument(self):\n        response = self.fetch(\"/get_argument?foo=bar\")\n        self.assertEqual(response.body, b\"bar\")\n        response = self.fetch(\"/get_argument?foo=\")\n        self.assertEqual(response.body, b\"\")\n        response = self.fetch(\"/get_argument\")\n        self.assertEqual(response.body, b\"default\")\n\n    def test_no_gzip(self):\n        response = self.fetch('/get_argument')\n        self.assertNotIn('Accept-Encoding', response.headers.get('Vary', ''))\n        self.assertNotIn('gzip', response.headers.get('Content-Encoding', ''))\n\n\nclass NonWSGIWebTests(WebTestCase):\n    def get_handlers(self):\n        return [(\"/flow_control\", FlowControlHandler),\n                (\"/empty_flush\", EmptyFlushCallbackHandler),\n                ]\n\n    def test_flow_control(self):\n        self.assertEqual(self.fetch(\"/flow_control\").body, b\"123\")\n\n    def test_empty_flush(self):\n        response = self.fetch(\"/empty_flush\")\n        self.assertEqual(response.body, b\"ok\")\n\n\n@wsgi_safe\nclass ErrorResponseTest(WebTestCase):\n    def get_handlers(self):\n        class DefaultHandler(RequestHandler):\n            def get(self):\n                if self.get_argument(\"status\", None):\n                    raise HTTPError(int(self.get_argument(\"status\")))\n                1 / 0\n\n        class WriteErrorHandler(RequestHandler):\n            def get(self):\n                if self.get_argument(\"status\", None):\n                    self.send_error(int(self.get_argument(\"status\")))\n                else:\n                    1 / 0\n\n            def write_error(self, status_code, **kwargs):\n                self.set_header(\"Content-Type\", \"text/plain\")\n                if \"exc_info\" in kwargs:\n                    self.write(\"Exception: %s\" % kwargs[\"exc_info\"][0].__name__)\n                else:\n                    self.write(\"Status: %d\" % status_code)\n\n        class GetErrorHtmlHandler(RequestHandler):\n            def get(self):\n                if self.get_argument(\"status\", None):\n                    self.send_error(int(self.get_argument(\"status\")))\n                else:\n                    1 / 0\n\n            def get_error_html(self, status_code, **kwargs):\n                self.set_header(\"Content-Type\", \"text/plain\")\n                if \"exception\" in kwargs:\n                    self.write(\"Exception: %s\" % sys.exc_info()[0].__name__)\n                else:\n                    self.write(\"Status: %d\" % status_code)\n\n        class FailedWriteErrorHandler(RequestHandler):\n            def get(self):\n                1 / 0\n\n            def write_error(self, status_code, **kwargs):\n                raise Exception(\"exception in write_error\")\n\n        return [url(\"/default\", DefaultHandler),\n                url(\"/write_error\", WriteErrorHandler),\n                url(\"/get_error_html\", GetErrorHtmlHandler),\n                url(\"/failed_write_error\", FailedWriteErrorHandler),\n                ]\n\n    def test_default(self):\n        with ExpectLog(app_log, \"Uncaught exception\"):\n            response = self.fetch(\"/default\")\n            self.assertEqual(response.code, 500)\n            self.assertTrue(b\"500: Internal Server Error\" in response.body)\n\n            response = self.fetch(\"/default?status=503\")\n            self.assertEqual(response.code, 503)\n            self.assertTrue(b\"503: Service Unavailable\" in response.body)\n\n    def test_write_error(self):\n        with ExpectLog(app_log, \"Uncaught exception\"):\n            response = self.fetch(\"/write_error\")\n            self.assertEqual(response.code, 500)\n            self.assertEqual(b\"Exception: ZeroDivisionError\", response.body)\n\n            response = self.fetch(\"/write_error?status=503\")\n            self.assertEqual(response.code, 503)\n            self.assertEqual(b\"Status: 503\", response.body)\n\n    def test_get_error_html(self):\n        with ExpectLog(app_log, \"Uncaught exception\"):\n            response = self.fetch(\"/get_error_html\")\n            self.assertEqual(response.code, 500)\n            self.assertEqual(b\"Exception: ZeroDivisionError\", response.body)\n\n            response = self.fetch(\"/get_error_html?status=503\")\n            self.assertEqual(response.code, 503)\n            self.assertEqual(b\"Status: 503\", response.body)\n\n    def test_failed_write_error(self):\n        with ExpectLog(app_log, \"Uncaught exception\"):\n            response = self.fetch(\"/failed_write_error\")\n            self.assertEqual(response.code, 500)\n            self.assertEqual(b\"\", response.body)\n\n\n@wsgi_safe\nclass StaticFileTest(WebTestCase):\n    # The expected MD5 hash of robots.txt, used in tests that call\n    # StaticFileHandler.get_version\n    robots_txt_hash = b\"f71d20196d4caf35b6a670db8c70b03d\"\n    static_dir = os.path.join(os.path.dirname(__file__), 'static')\n\n    def get_handlers(self):\n        class StaticUrlHandler(RequestHandler):\n            def get(self, path):\n                with_v = int(self.get_argument('include_version', 1))\n                self.write(self.static_url(path, include_version=with_v))\n\n        class AbsoluteStaticUrlHandler(StaticUrlHandler):\n            include_host = True\n\n        class OverrideStaticUrlHandler(RequestHandler):\n            def get(self, path):\n                do_include = bool(self.get_argument(\"include_host\"))\n                self.include_host = not do_include\n\n                regular_url = self.static_url(path)\n                override_url = self.static_url(path, include_host=do_include)\n                if override_url == regular_url:\n                    return self.write(str(False))\n\n                protocol = self.request.protocol + \"://\"\n                protocol_length = len(protocol)\n                check_regular = regular_url.find(protocol, 0, protocol_length)\n                check_override = override_url.find(protocol, 0, protocol_length)\n\n                if do_include:\n                    result = (check_override == 0 and check_regular == -1)\n                else:\n                    result = (check_override == -1 and check_regular == 0)\n                self.write(str(result))\n\n        return [('/static_url/(.*)', StaticUrlHandler),\n                ('/abs_static_url/(.*)', AbsoluteStaticUrlHandler),\n                ('/override_static_url/(.*)', OverrideStaticUrlHandler)]\n\n    def get_app_kwargs(self):\n        return dict(static_path=relpath('static'))\n\n    def test_static_files(self):\n        response = self.fetch('/robots.txt')\n        self.assertTrue(b\"Disallow: /\" in response.body)\n\n        response = self.fetch('/static/robots.txt')\n        self.assertTrue(b\"Disallow: /\" in response.body)\n\n    def test_static_url(self):\n        response = self.fetch(\"/static_url/robots.txt\")\n        self.assertEqual(response.body,\n                         b\"/static/robots.txt?v=\" + self.robots_txt_hash)\n\n    def test_absolute_static_url(self):\n        response = self.fetch(\"/abs_static_url/robots.txt\")\n        self.assertEqual(response.body, (\n            utf8(self.get_url(\"/\")) +\n            b\"static/robots.txt?v=\" +\n            self.robots_txt_hash\n        ))\n\n    def test_relative_version_exclusion(self):\n        response = self.fetch(\"/static_url/robots.txt?include_version=0\")\n        self.assertEqual(response.body, b\"/static/robots.txt\")\n\n    def test_absolute_version_exclusion(self):\n        response = self.fetch(\"/abs_static_url/robots.txt?include_version=0\")\n        self.assertEqual(response.body,\n                         utf8(self.get_url(\"/\") + \"static/robots.txt\"))\n\n    def test_include_host_override(self):\n        self._trigger_include_host_check(False)\n        self._trigger_include_host_check(True)\n\n    def _trigger_include_host_check(self, include_host):\n        path = \"/override_static_url/robots.txt?include_host=%s\"\n        response = self.fetch(path % int(include_host))\n        self.assertEqual(response.body, utf8(str(True)))\n\n    def test_static_304_if_modified_since(self):\n        response1 = self.fetch(\"/static/robots.txt\")\n        response2 = self.fetch(\"/static/robots.txt\", headers={\n            'If-Modified-Since': response1.headers['Last-Modified']})\n        self.assertEqual(response2.code, 304)\n        self.assertTrue('Content-Length' not in response2.headers)\n        self.assertTrue('Last-Modified' not in response2.headers)\n\n    def test_static_304_if_none_match(self):\n        response1 = self.fetch(\"/static/robots.txt\")\n        response2 = self.fetch(\"/static/robots.txt\", headers={\n            'If-None-Match': response1.headers['Etag']})\n        self.assertEqual(response2.code, 304)\n\n    def test_static_if_modified_since_pre_epoch(self):\n        # On windows, the functions that work with time_t do not accept\n        # negative values, and at least one client (processing.js) seems\n        # to use if-modified-since 1/1/1960 as a cache-busting technique.\n        response = self.fetch(\"/static/robots.txt\", headers={\n            'If-Modified-Since': 'Fri, 01 Jan 1960 00:00:00 GMT'})\n        self.assertEqual(response.code, 200)\n\n    def test_static_if_modified_since_time_zone(self):\n        # Instead of the value from Last-Modified, make requests with times\n        # chosen just before and after the known modification time\n        # of the file to ensure that the right time zone is being used\n        # when parsing If-Modified-Since.\n        stat = os.stat(relpath('static/robots.txt'))\n\n        response = self.fetch('/static/robots.txt', headers={\n            'If-Modified-Since': format_timestamp(stat.st_mtime - 1)})\n        self.assertEqual(response.code, 200)\n        response = self.fetch('/static/robots.txt', headers={\n            'If-Modified-Since': format_timestamp(stat.st_mtime + 1)})\n        self.assertEqual(response.code, 304)\n\n    def test_static_etag(self):\n        response = self.fetch('/static/robots.txt')\n        self.assertEqual(utf8(response.headers.get(\"Etag\")),\n                         b'\"' + self.robots_txt_hash + b'\"')\n\n    def test_static_with_range(self):\n        response = self.fetch('/static/robots.txt', headers={\n            'Range': 'bytes=0-9'})\n        self.assertEqual(response.code, 206)\n        self.assertEqual(response.body, b\"User-agent\")\n        self.assertEqual(utf8(response.headers.get(\"Etag\")),\n                         b'\"' + self.robots_txt_hash + b'\"')\n        self.assertEqual(response.headers.get(\"Content-Length\"), \"10\")\n        self.assertEqual(response.headers.get(\"Content-Range\"),\n                         \"bytes 0-9/26\")\n\n    def test_static_with_range_full_file(self):\n        response = self.fetch('/static/robots.txt', headers={\n            'Range': 'bytes=0-'})\n        # Note: Chrome refuses to play audio if it gets an HTTP 206 in response\n        # to ``Range: bytes=0-`` :(\n        self.assertEqual(response.code, 200)\n        robots_file_path = os.path.join(self.static_dir, \"robots.txt\")\n        with open(robots_file_path) as f:\n            self.assertEqual(response.body, utf8(f.read()))\n        self.assertEqual(response.headers.get(\"Content-Length\"), \"26\")\n        self.assertEqual(response.headers.get(\"Content-Range\"), None)\n\n    def test_static_with_range_full_past_end(self):\n        response = self.fetch('/static/robots.txt', headers={\n            'Range': 'bytes=0-10000000'})\n        self.assertEqual(response.code, 200)\n        robots_file_path = os.path.join(self.static_dir, \"robots.txt\")\n        with open(robots_file_path) as f:\n            self.assertEqual(response.body, utf8(f.read()))\n        self.assertEqual(response.headers.get(\"Content-Length\"), \"26\")\n        self.assertEqual(response.headers.get(\"Content-Range\"), None)\n\n    def test_static_with_range_partial_past_end(self):\n        response = self.fetch('/static/robots.txt', headers={\n            'Range': 'bytes=1-10000000'})\n        self.assertEqual(response.code, 206)\n        robots_file_path = os.path.join(self.static_dir, \"robots.txt\")\n        with open(robots_file_path) as f:\n            self.assertEqual(response.body, utf8(f.read()[1:]))\n        self.assertEqual(response.headers.get(\"Content-Length\"), \"25\")\n        self.assertEqual(response.headers.get(\"Content-Range\"), \"bytes 1-25/26\")\n\n    def test_static_with_range_end_edge(self):\n        response = self.fetch('/static/robots.txt', headers={\n            'Range': 'bytes=22-'})\n        self.assertEqual(response.body, b\": /\\n\")\n        self.assertEqual(response.headers.get(\"Content-Length\"), \"4\")\n        self.assertEqual(response.headers.get(\"Content-Range\"),\n                         \"bytes 22-25/26\")\n\n    def test_static_with_range_neg_end(self):\n        response = self.fetch('/static/robots.txt', headers={\n            'Range': 'bytes=-4'})\n        self.assertEqual(response.body, b\": /\\n\")\n        self.assertEqual(response.headers.get(\"Content-Length\"), \"4\")\n        self.assertEqual(response.headers.get(\"Content-Range\"),\n                         \"bytes 22-25/26\")\n\n    def test_static_invalid_range(self):\n        response = self.fetch('/static/robots.txt', headers={\n            'Range': 'asdf'})\n        self.assertEqual(response.code, 200)\n\n    def test_static_unsatisfiable_range_zero_suffix(self):\n        response = self.fetch('/static/robots.txt', headers={\n            'Range': 'bytes=-0'})\n        self.assertEqual(response.headers.get(\"Content-Range\"),\n                         \"bytes */26\")\n        self.assertEqual(response.code, 416)\n\n    def test_static_unsatisfiable_range_invalid_start(self):\n        response = self.fetch('/static/robots.txt', headers={\n            'Range': 'bytes=26'})\n        self.assertEqual(response.code, 416)\n        self.assertEqual(response.headers.get(\"Content-Range\"),\n                         \"bytes */26\")\n\n    def test_static_head(self):\n        response = self.fetch('/static/robots.txt', method='HEAD')\n        self.assertEqual(response.code, 200)\n        # No body was returned, but we did get the right content length.\n        self.assertEqual(response.body, b'')\n        self.assertEqual(response.headers['Content-Length'], '26')\n        self.assertEqual(utf8(response.headers['Etag']),\n                         b'\"' + self.robots_txt_hash + b'\"')\n\n    def test_static_head_range(self):\n        response = self.fetch('/static/robots.txt', method='HEAD',\n                              headers={'Range': 'bytes=1-4'})\n        self.assertEqual(response.code, 206)\n        self.assertEqual(response.body, b'')\n        self.assertEqual(response.headers['Content-Length'], '4')\n        self.assertEqual(utf8(response.headers['Etag']),\n                         b'\"' + self.robots_txt_hash + b'\"')\n\n    def test_static_range_if_none_match(self):\n        response = self.fetch('/static/robots.txt', headers={\n            'Range': 'bytes=1-4',\n            'If-None-Match': b'\"' + self.robots_txt_hash + b'\"'})\n        self.assertEqual(response.code, 304)\n        self.assertEqual(response.body, b'')\n        self.assertTrue('Content-Length' not in response.headers)\n        self.assertEqual(utf8(response.headers['Etag']),\n                         b'\"' + self.robots_txt_hash + b'\"')\n\n    def test_static_404(self):\n        response = self.fetch('/static/blarg')\n        self.assertEqual(response.code, 404)\n\n\n@wsgi_safe\nclass StaticDefaultFilenameTest(WebTestCase):\n    def get_app_kwargs(self):\n        return dict(static_path=relpath('static'),\n                    static_handler_args=dict(default_filename='index.html'))\n\n    def get_handlers(self):\n        return []\n\n    def test_static_default_filename(self):\n        response = self.fetch('/static/dir/', follow_redirects=False)\n        self.assertEqual(response.code, 200)\n        self.assertEqual(b'this is the index\\n', response.body)\n\n    def test_static_default_redirect(self):\n        response = self.fetch('/static/dir', follow_redirects=False)\n        self.assertEqual(response.code, 301)\n        self.assertTrue(response.headers['Location'].endswith('/static/dir/'))\n\n\n@wsgi_safe\nclass StaticFileWithPathTest(WebTestCase):\n    def get_app_kwargs(self):\n        return dict(static_path=relpath('static'),\n                    static_handler_args=dict(default_filename='index.html'))\n\n    def get_handlers(self):\n        return [(\"/foo/(.*)\", StaticFileHandler, {\n            \"path\": relpath(\"templates/\"),\n        })]\n\n    def test_serve(self):\n        response = self.fetch(\"/foo/utf8.html\")\n        self.assertEqual(response.body, b\"H\\xc3\\xa9llo\\n\")\n\n\n@wsgi_safe\nclass CustomStaticFileTest(WebTestCase):\n    def get_handlers(self):\n        class MyStaticFileHandler(StaticFileHandler):\n            @classmethod\n            def make_static_url(cls, settings, path):\n                version_hash = cls.get_version(settings, path)\n                extension_index = path.rindex('.')\n                before_version = path[:extension_index]\n                after_version = path[(extension_index + 1):]\n                return '/static/%s.%s.%s' % (before_version, version_hash,\n                                             after_version)\n\n            def parse_url_path(self, url_path):\n                extension_index = url_path.rindex('.')\n                version_index = url_path.rindex('.', 0, extension_index)\n                return '%s%s' % (url_path[:version_index],\n                                 url_path[extension_index:])\n\n            @classmethod\n            def get_absolute_path(cls, settings, path):\n                return 'CustomStaticFileTest:' + path\n\n            def validate_absolute_path(self, root, absolute_path):\n                return absolute_path\n\n            @classmethod\n            def get_content(self, path, start=None, end=None):\n                assert start is None and end is None\n                if path == 'CustomStaticFileTest:foo.txt':\n                    return b'bar'\n                raise Exception(\"unexpected path %r\" % path)\n\n            def get_modified_time(self):\n                return None\n\n            @classmethod\n            def get_version(cls, settings, path):\n                return \"42\"\n\n        class StaticUrlHandler(RequestHandler):\n            def get(self, path):\n                self.write(self.static_url(path))\n\n        self.static_handler_class = MyStaticFileHandler\n\n        return [(\"/static_url/(.*)\", StaticUrlHandler)]\n\n    def get_app_kwargs(self):\n        return dict(static_path=\"dummy\",\n                    static_handler_class=self.static_handler_class)\n\n    def test_serve(self):\n        response = self.fetch(\"/static/foo.42.txt\")\n        self.assertEqual(response.body, b\"bar\")\n\n    def test_static_url(self):\n        with ExpectLog(gen_log, \"Could not open static file\", required=False):\n            response = self.fetch(\"/static_url/foo.txt\")\n            self.assertEqual(response.body, b\"/static/foo.42.txt\")\n\n\n@wsgi_safe\nclass HostMatchingTest(WebTestCase):\n    class Handler(RequestHandler):\n        def initialize(self, reply):\n            self.reply = reply\n\n        def get(self):\n            self.write(self.reply)\n\n    def get_handlers(self):\n        return [(\"/foo\", HostMatchingTest.Handler, {\"reply\": \"wildcard\"})]\n\n    def test_host_matching(self):\n        self.app.add_handlers(\"www.example.com\",\n                              [(\"/foo\", HostMatchingTest.Handler, {\"reply\": \"[0]\"})])\n        self.app.add_handlers(r\"www\\.example\\.com\",\n                              [(\"/bar\", HostMatchingTest.Handler, {\"reply\": \"[1]\"})])\n        self.app.add_handlers(\"www.example.com\",\n                              [(\"/baz\", HostMatchingTest.Handler, {\"reply\": \"[2]\"})])\n\n        response = self.fetch(\"/foo\")\n        self.assertEqual(response.body, b\"wildcard\")\n        response = self.fetch(\"/bar\")\n        self.assertEqual(response.code, 404)\n        response = self.fetch(\"/baz\")\n        self.assertEqual(response.code, 404)\n\n        response = self.fetch(\"/foo\", headers={'Host': 'www.example.com'})\n        self.assertEqual(response.body, b\"[0]\")\n        response = self.fetch(\"/bar\", headers={'Host': 'www.example.com'})\n        self.assertEqual(response.body, b\"[1]\")\n        response = self.fetch(\"/baz\", headers={'Host': 'www.example.com'})\n        self.assertEqual(response.body, b\"[2]\")\n\n\n@wsgi_safe\nclass NamedURLSpecGroupsTest(WebTestCase):\n    def get_handlers(self):\n        class EchoHandler(RequestHandler):\n            def get(self, path):\n                self.write(path)\n\n        return [(\"/str/(?P<path>.*)\", EchoHandler),\n                (u(\"/unicode/(?P<path>.*)\"), EchoHandler)]\n\n    def test_named_urlspec_groups(self):\n        response = self.fetch(\"/str/foo\")\n        self.assertEqual(response.body, b\"foo\")\n\n        response = self.fetch(\"/unicode/bar\")\n        self.assertEqual(response.body, b\"bar\")\n\n\n@wsgi_safe\nclass ClearHeaderTest(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        def get(self):\n            self.set_header(\"h1\", \"foo\")\n            self.set_header(\"h2\", \"bar\")\n            self.clear_header(\"h1\")\n            self.clear_header(\"nonexistent\")\n\n    def test_clear_header(self):\n        response = self.fetch(\"/\")\n        self.assertTrue(\"h1\" not in response.headers)\n        self.assertEqual(response.headers[\"h2\"], \"bar\")\n\n\n@wsgi_safe\nclass Header304Test(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        def get(self):\n            self.set_header(\"Content-Language\", \"en_US\")\n            self.write(\"hello\")\n\n    def test_304_headers(self):\n        response1 = self.fetch('/')\n        self.assertEqual(response1.headers[\"Content-Length\"], \"5\")\n        self.assertEqual(response1.headers[\"Content-Language\"], \"en_US\")\n\n        response2 = self.fetch('/', headers={\n            'If-None-Match': response1.headers[\"Etag\"]})\n        self.assertEqual(response2.code, 304)\n        self.assertTrue(\"Content-Length\" not in response2.headers)\n        self.assertTrue(\"Content-Language\" not in response2.headers)\n        # Not an entity header, but should not be added to 304s by chunking\n        self.assertTrue(\"Transfer-Encoding\" not in response2.headers)\n\n\n@wsgi_safe\nclass StatusReasonTest(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        def get(self):\n            reason = self.request.arguments.get('reason', [])\n            self.set_status(int(self.get_argument('code')),\n                            reason=reason[0] if reason else None)\n\n    def get_http_client(self):\n        # simple_httpclient only: curl doesn't expose the reason string\n        return SimpleAsyncHTTPClient(io_loop=self.io_loop)\n\n    def test_status(self):\n        response = self.fetch(\"/?code=304\")\n        self.assertEqual(response.code, 304)\n        self.assertEqual(response.reason, \"Not Modified\")\n        response = self.fetch(\"/?code=304&reason=Foo\")\n        self.assertEqual(response.code, 304)\n        self.assertEqual(response.reason, \"Foo\")\n        response = self.fetch(\"/?code=682&reason=Bar\")\n        self.assertEqual(response.code, 682)\n        self.assertEqual(response.reason, \"Bar\")\n        with ExpectLog(app_log, 'Uncaught exception'):\n            response = self.fetch(\"/?code=682\")\n        self.assertEqual(response.code, 500)\n\n\n@wsgi_safe\nclass DateHeaderTest(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        def get(self):\n            self.write(\"hello\")\n\n    def test_date_header(self):\n        response = self.fetch('/')\n        header_date = datetime.datetime(\n            *email.utils.parsedate(response.headers['Date'])[:6])\n        self.assertTrue(header_date - datetime.datetime.utcnow() <\n                        datetime.timedelta(seconds=2))\n\n\n@wsgi_safe\nclass RaiseWithReasonTest(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        def get(self):\n            raise HTTPError(682, reason=\"Foo\")\n\n    def get_http_client(self):\n        # simple_httpclient only: curl doesn't expose the reason string\n        return SimpleAsyncHTTPClient(io_loop=self.io_loop)\n\n    def test_raise_with_reason(self):\n        response = self.fetch(\"/\")\n        self.assertEqual(response.code, 682)\n        self.assertEqual(response.reason, \"Foo\")\n        self.assertIn(b'682: Foo', response.body)\n\n    def test_httperror_str(self):\n        self.assertEqual(str(HTTPError(682, reason=\"Foo\")), \"HTTP 682: Foo\")\n\n\n@wsgi_safe\nclass ErrorHandlerXSRFTest(WebTestCase):\n    def get_handlers(self):\n        # note that if the handlers list is empty we get the default_host\n        # redirect fallback instead of a 404, so test with both an\n        # explicitly defined error handler and an implicit 404.\n        return [('/error', ErrorHandler, dict(status_code=417))]\n\n    def get_app_kwargs(self):\n        return dict(xsrf_cookies=True)\n\n    def test_error_xsrf(self):\n        response = self.fetch('/error', method='POST', body='')\n        self.assertEqual(response.code, 417)\n\n    def test_404_xsrf(self):\n        response = self.fetch('/404', method='POST', body='')\n        self.assertEqual(response.code, 404)\n\n\nclass GzipTestCase(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        def get(self):\n            if self.get_argument('vary', None):\n                self.set_header('Vary', self.get_argument('vary'))\n            self.write('hello world')\n\n    def get_app_kwargs(self):\n        return dict(gzip=True)\n\n    def test_gzip(self):\n        response = self.fetch('/')\n        self.assertEqual(response.headers['Content-Encoding'], 'gzip')\n        self.assertEqual(response.headers['Vary'], 'Accept-Encoding')\n\n    def test_gzip_not_requested(self):\n        response = self.fetch('/', use_gzip=False)\n        self.assertNotIn('Content-Encoding', response.headers)\n        self.assertEqual(response.headers['Vary'], 'Accept-Encoding')\n\n    def test_vary_already_present(self):\n        response = self.fetch('/?vary=Accept-Language')\n        self.assertEqual(response.headers['Vary'],\n                         'Accept-Language, Accept-Encoding')\n\n\n@wsgi_safe\nclass PathArgsInPrepareTest(WebTestCase):\n    class Handler(RequestHandler):\n        def prepare(self):\n            self.write(dict(args=self.path_args, kwargs=self.path_kwargs))\n\n        def get(self, path):\n            assert path == 'foo'\n            self.finish()\n\n    def get_handlers(self):\n        return [('/pos/(.*)', self.Handler),\n                ('/kw/(?P<path>.*)', self.Handler)]\n\n    def test_pos(self):\n        response = self.fetch('/pos/foo')\n        response.rethrow()\n        data = json_decode(response.body)\n        self.assertEqual(data, {'args': ['foo'], 'kwargs': {}})\n\n    def test_kw(self):\n        response = self.fetch('/kw/foo')\n        response.rethrow()\n        data = json_decode(response.body)\n        self.assertEqual(data, {'args': [], 'kwargs': {'path': 'foo'}})\n\n\n@wsgi_safe\nclass ClearAllCookiesTest(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        def get(self):\n            self.clear_all_cookies()\n            self.write('ok')\n\n    def test_clear_all_cookies(self):\n        response = self.fetch('/', headers={'Cookie': 'foo=bar; baz=xyzzy'})\n        set_cookies = sorted(response.headers.get_list('Set-Cookie'))\n        self.assertTrue(set_cookies[0].startswith('baz=;'))\n        self.assertTrue(set_cookies[1].startswith('foo=;'))\n\n\nclass PermissionError(Exception):\n    pass\n\n\n@wsgi_safe\nclass ExceptionHandlerTest(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        def get(self):\n            exc = self.get_argument('exc')\n            if exc == 'http':\n                raise HTTPError(410, \"no longer here\")\n            elif exc == 'zero':\n                1 / 0\n            elif exc == 'permission':\n                raise PermissionError('not allowed')\n\n        def write_error(self, status_code, **kwargs):\n            if 'exc_info' in kwargs:\n                typ, value, tb = kwargs['exc_info']\n                if isinstance(value, PermissionError):\n                    self.set_status(403)\n                    self.write('PermissionError')\n                    return\n            RequestHandler.write_error(self, status_code, **kwargs)\n\n        def log_exception(self, typ, value, tb):\n            if isinstance(value, PermissionError):\n                app_log.warning('custom logging for PermissionError: %s',\n                                value.args[0])\n            else:\n                RequestHandler.log_exception(self, typ, value, tb)\n\n    def test_http_error(self):\n        # HTTPErrors are logged as warnings with no stack trace.\n        # TODO: extend ExpectLog to test this more precisely\n        with ExpectLog(gen_log, '.*no longer here'):\n            response = self.fetch('/?exc=http')\n            self.assertEqual(response.code, 410)\n\n    def test_unknown_error(self):\n        # Unknown errors are logged as errors with a stack trace.\n        with ExpectLog(app_log, 'Uncaught exception'):\n            response = self.fetch('/?exc=zero')\n            self.assertEqual(response.code, 500)\n\n    def test_known_error(self):\n        # log_exception can override logging behavior, and write_error\n        # can override the response.\n        with ExpectLog(app_log,\n                       'custom logging for PermissionError: not allowed'):\n            response = self.fetch('/?exc=permission')\n            self.assertEqual(response.code, 403)\n\n\n@wsgi_safe\nclass UIMethodUIModuleTest(SimpleHandlerTestCase):\n    \"\"\"Test that UI methods and modules are created correctly and\n    associated with the handler.\n    \"\"\"\n    class Handler(RequestHandler):\n        def get(self):\n            self.render('foo.html')\n\n        def value(self):\n            return self.get_argument(\"value\")\n\n    def get_app_kwargs(self):\n        def my_ui_method(handler, x):\n            return \"In my_ui_method(%s) with handler value %s.\" % (\n                x, handler.value())\n        class MyModule(UIModule):\n            def render(self, x):\n                return \"In MyModule(%s) with handler value %s.\" % (\n                    x, self.handler.value())\n\n        loader = DictLoader({\n            'foo.html': '{{ my_ui_method(42) }} {% module MyModule(123) %}',\n        })\n        return dict(template_loader=loader,\n                    ui_methods={'my_ui_method': my_ui_method},\n                    ui_modules={'MyModule': MyModule})\n\n    def tearDown(self):\n        super(UIMethodUIModuleTest, self).tearDown()\n        # TODO: fix template loader caching so this isn't necessary.\n        RequestHandler._template_loaders.clear()\n\n    def test_ui_method(self):\n        response = self.fetch('/?value=asdf')\n        self.assertEqual(response.body,\n                         b'In my_ui_method(42) with handler value asdf. '\n                         b'In MyModule(123) with handler value asdf.')\n\n\n@wsgi_safe\nclass GetArgumentErrorTest(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        def get(self):\n            try:\n                self.get_argument('foo')\n                self.write({})\n            except MissingArgumentError as e:\n                self.write({'arg_name': e.arg_name,\n                            'log_message': e.log_message})\n\n    def test_catch_error(self):\n        response = self.fetch('/')\n        self.assertEqual(json_decode(response.body),\n                         {'arg_name': 'foo',\n                          'log_message': 'Missing argument foo'})\n\n\nclass MultipleExceptionTest(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        exc_count = 0\n\n        @asynchronous\n        def get(self):\n            from tornado.ioloop import IOLoop\n            IOLoop.current().add_callback(lambda: 1 / 0)\n            IOLoop.current().add_callback(lambda: 1 / 0)\n\n        def log_exception(self, typ, value, tb):\n            MultipleExceptionTest.Handler.exc_count += 1\n\n    def test_multi_exception(self):\n        # This test verifies that multiple exceptions raised into the same\n        # ExceptionStackContext do not generate extraneous log entries\n        # due to \"Cannot send error response after headers written\".\n        # log_exception is called, but it does not proceed to send_error.\n        response = self.fetch('/')\n        self.assertEqual(response.code, 500)\n        response = self.fetch('/')\n        self.assertEqual(response.code, 500)\n        # Each of our two requests generated two exceptions, we should have\n        # seen at least three of them by now (the fourth may still be\n        # in the queue).\n        self.assertGreater(MultipleExceptionTest.Handler.exc_count, 2)\n\n\n@wsgi_safe\nclass SetCurrentUserTest(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        def prepare(self):\n            self.current_user = 'Ben'\n\n        def get(self):\n            self.write('Hello %s' % self.current_user)\n\n    def test_set_current_user(self):\n        # Ensure that current_user can be assigned to normally for apps\n        # that want to forgo the lazy get_current_user property\n        response = self.fetch('/')\n        self.assertEqual(response.body, b'Hello Ben')\n\n\n@wsgi_safe\nclass UnimplementedHTTPMethodsTest(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        pass\n\n    def test_unimplemented_standard_methods(self):\n        for method in ['HEAD', 'GET', 'DELETE', 'OPTIONS']:\n            response = self.fetch('/', method=method)\n            self.assertEqual(response.code, 405)\n        for method in ['POST', 'PUT']:\n            response = self.fetch('/', method=method, body=b'')\n            self.assertEqual(response.code, 405)\n\n\nclass UnimplementedNonStandardMethodsTest(SimpleHandlerTestCase):\n    # wsgiref.validate complains about unknown methods in a way that makes\n    # this test not wsgi_safe.\n    class Handler(RequestHandler):\n        def other(self):\n            # Even though this method exists, it won't get called automatically\n            # because it is not in SUPPORTED_METHODS.\n            self.write('other')\n\n    def test_unimplemented_patch(self):\n        # PATCH is recently standardized; Tornado supports it by default\n        # but wsgiref.validate doesn't like it.\n        response = self.fetch('/', method='PATCH', body=b'')\n        self.assertEqual(response.code, 405)\n\n    def test_unimplemented_other(self):\n        response = self.fetch('/', method='OTHER',\n                              allow_nonstandard_methods=True)\n        self.assertEqual(response.code, 405)\n\n\n@wsgi_safe\nclass AllHTTPMethodsTest(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        def method(self):\n            self.write(self.request.method)\n\n        get = delete = options = post = put = method\n\n    def test_standard_methods(self):\n        response = self.fetch('/', method='HEAD')\n        self.assertEqual(response.body, b'')\n        for method in ['GET', 'DELETE', 'OPTIONS']:\n            response = self.fetch('/', method=method)\n            self.assertEqual(response.body, utf8(method))\n        for method in ['POST', 'PUT']:\n            response = self.fetch('/', method=method, body=b'')\n            self.assertEqual(response.body, utf8(method))\n\n\nclass PatchMethodTest(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        SUPPORTED_METHODS = RequestHandler.SUPPORTED_METHODS + ('OTHER',)\n\n        def patch(self):\n            self.write('patch')\n\n        def other(self):\n            self.write('other')\n\n    def test_patch(self):\n        response = self.fetch('/', method='PATCH', body=b'')\n        self.assertEqual(response.body, b'patch')\n\n    def test_other(self):\n        response = self.fetch('/', method='OTHER',\n                              allow_nonstandard_methods=True)\n        self.assertEqual(response.body, b'other')\n\n\n@wsgi_safe\nclass FinishInPrepareTest(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        def prepare(self):\n            self.finish('done')\n\n        def get(self):\n            # It's difficult to assert for certain that a method did not\n            # or will not be called in an asynchronous context, but this\n            # will be logged noisily if it is reached.\n            raise Exception('should not reach this method')\n\n    def test_finish_in_prepare(self):\n        response = self.fetch('/')\n        self.assertEqual(response.body, b'done')\n",
            "new_file_content": "from __future__ import absolute_import, division, print_function, with_statement\nfrom tornado import gen\nfrom tornado.escape import json_decode, utf8, to_unicode, recursive_unicode, native_str, to_basestring\nfrom tornado.httputil import format_timestamp\nfrom tornado.iostream import IOStream\nfrom tornado.log import app_log, gen_log\nfrom tornado.simple_httpclient import SimpleAsyncHTTPClient\nfrom tornado.template import DictLoader\nfrom tornado.testing import AsyncHTTPTestCase, ExpectLog\nfrom tornado.test.util import unittest\nfrom tornado.util import u, bytes_type, ObjectDict, unicode_type\nfrom tornado.web import RequestHandler, authenticated, Application, asynchronous, url, HTTPError, StaticFileHandler, _create_signature, create_signed_value, ErrorHandler, UIModule, MissingArgumentError\n\nimport binascii\nimport datetime\nimport email.utils\nimport logging\nimport os\nimport re\nimport socket\nimport sys\n\nwsgi_safe_tests = []\n\nrelpath = lambda *a: os.path.join(os.path.dirname(__file__), *a)\n\n\ndef wsgi_safe(cls):\n    wsgi_safe_tests.append(cls)\n    return cls\n\n\nclass WebTestCase(AsyncHTTPTestCase):\n    \"\"\"Base class for web tests that also supports WSGI mode.\n\n    Override get_handlers and get_app_kwargs instead of get_app.\n    Append to wsgi_safe to have it run in wsgi_test as well.\n    \"\"\"\n    def get_app(self):\n        self.app = Application(self.get_handlers(), **self.get_app_kwargs())\n        return self.app\n\n    def get_handlers(self):\n        raise NotImplementedError()\n\n    def get_app_kwargs(self):\n        return {}\n\n\nclass SimpleHandlerTestCase(WebTestCase):\n    \"\"\"Simplified base class for tests that work with a single handler class.\n\n    To use, define a nested class named ``Handler``.\n    \"\"\"\n    def get_handlers(self):\n        return [('/', self.Handler)]\n\n\nclass CookieTestRequestHandler(RequestHandler):\n    # stub out enough methods to make the secure_cookie functions work\n    def __init__(self):\n        # don't call super.__init__\n        self._cookies = {}\n        self.application = ObjectDict(settings=dict(cookie_secret='0123456789'))\n\n    def get_cookie(self, name):\n        return self._cookies.get(name)\n\n    def set_cookie(self, name, value, expires_days=None):\n        self._cookies[name] = value\n\n\nclass SecureCookieTest(unittest.TestCase):\n    def test_round_trip(self):\n        handler = CookieTestRequestHandler()\n        handler.set_secure_cookie('foo', b'bar')\n        self.assertEqual(handler.get_secure_cookie('foo'), b'bar')\n\n    def test_cookie_tampering_future_timestamp(self):\n        handler = CookieTestRequestHandler()\n        # this string base64-encodes to '12345678'\n        handler.set_secure_cookie('foo', binascii.a2b_hex(b'd76df8e7aefc'))\n        cookie = handler._cookies['foo']\n        match = re.match(br'12345678\\|([0-9]+)\\|([0-9a-f]+)', cookie)\n        self.assertTrue(match)\n        timestamp = match.group(1)\n        sig = match.group(2)\n        self.assertEqual(\n            _create_signature(handler.application.settings[\"cookie_secret\"],\n                              'foo', '12345678', timestamp),\n            sig)\n        # shifting digits from payload to timestamp doesn't alter signature\n        # (this is not desirable behavior, just confirming that that's how it\n        # works)\n        self.assertEqual(\n            _create_signature(handler.application.settings[\"cookie_secret\"],\n                              'foo', '1234', b'5678' + timestamp),\n            sig)\n        # tamper with the cookie\n        handler._cookies['foo'] = utf8('1234|5678%s|%s' % (\n            to_basestring(timestamp), to_basestring(sig)))\n        # it gets rejected\n        with ExpectLog(gen_log, \"Cookie timestamp in future\"):\n            self.assertTrue(handler.get_secure_cookie('foo') is None)\n\n    def test_arbitrary_bytes(self):\n        # Secure cookies accept arbitrary data (which is base64 encoded).\n        # Note that normal cookies accept only a subset of ascii.\n        handler = CookieTestRequestHandler()\n        handler.set_secure_cookie('foo', b'\\xe9')\n        self.assertEqual(handler.get_secure_cookie('foo'), b'\\xe9')\n\n\nclass CookieTest(WebTestCase):\n    def get_handlers(self):\n        class SetCookieHandler(RequestHandler):\n            def get(self):\n                # Try setting cookies with different argument types\n                # to ensure that everything gets encoded correctly\n                self.set_cookie(\"str\", \"asdf\")\n                self.set_cookie(\"unicode\", u(\"qwer\"))\n                self.set_cookie(\"bytes\", b\"zxcv\")\n\n        class GetCookieHandler(RequestHandler):\n            def get(self):\n                self.write(self.get_cookie(\"foo\", \"default\"))\n\n        class SetCookieDomainHandler(RequestHandler):\n            def get(self):\n                # unicode domain and path arguments shouldn't break things\n                # either (see bug #285)\n                self.set_cookie(\"unicode_args\", \"blah\", domain=u(\"foo.com\"),\n                                path=u(\"/foo\"))\n\n        class SetCookieSpecialCharHandler(RequestHandler):\n            def get(self):\n                self.set_cookie(\"equals\", \"a=b\")\n                self.set_cookie(\"semicolon\", \"a;b\")\n                self.set_cookie(\"quote\", 'a\"b')\n\n        class SetCookieOverwriteHandler(RequestHandler):\n            def get(self):\n                self.set_cookie(\"a\", \"b\", domain=\"example.com\")\n                self.set_cookie(\"c\", \"d\", domain=\"example.com\")\n                # A second call with the same name clobbers the first.\n                # Attributes from the first call are not carried over.\n                self.set_cookie(\"a\", \"e\")\n\n        return [(\"/set\", SetCookieHandler),\n                (\"/get\", GetCookieHandler),\n                (\"/set_domain\", SetCookieDomainHandler),\n                (\"/special_char\", SetCookieSpecialCharHandler),\n                (\"/set_overwrite\", SetCookieOverwriteHandler),\n                ]\n\n    def test_set_cookie(self):\n        response = self.fetch(\"/set\")\n        self.assertEqual(sorted(response.headers.get_list(\"Set-Cookie\")),\n                         [\"bytes=zxcv; Path=/\",\n                          \"str=asdf; Path=/\",\n                          \"unicode=qwer; Path=/\",\n                          ])\n\n    def test_get_cookie(self):\n        response = self.fetch(\"/get\", headers={\"Cookie\": \"foo=bar\"})\n        self.assertEqual(response.body, b\"bar\")\n\n        response = self.fetch(\"/get\", headers={\"Cookie\": 'foo=\"bar\"'})\n        self.assertEqual(response.body, b\"bar\")\n\n        response = self.fetch(\"/get\", headers={\"Cookie\": \"/=exception;\"})\n        self.assertEqual(response.body, b\"default\")\n\n    def test_set_cookie_domain(self):\n        response = self.fetch(\"/set_domain\")\n        self.assertEqual(response.headers.get_list(\"Set-Cookie\"),\n                         [\"unicode_args=blah; Domain=foo.com; Path=/foo\"])\n\n    def test_cookie_special_char(self):\n        response = self.fetch(\"/special_char\")\n        headers = sorted(response.headers.get_list(\"Set-Cookie\"))\n        self.assertEqual(len(headers), 3)\n        self.assertEqual(headers[0], 'equals=\"a=b\"; Path=/')\n        self.assertEqual(headers[1], 'quote=\"a\\\\\"b\"; Path=/')\n        # python 2.7 octal-escapes the semicolon; older versions leave it alone\n        self.assertTrue(headers[2] in ('semicolon=\"a;b\"; Path=/',\n                                       'semicolon=\"a\\\\073b\"; Path=/'),\n                        headers[2])\n\n        data = [('foo=a=b', 'a=b'),\n                ('foo=\"a=b\"', 'a=b'),\n                ('foo=\"a;b\"', 'a;b'),\n                # ('foo=a\\\\073b', 'a;b'),  # even encoded, \";\" is a delimiter\n                ('foo=\"a\\\\073b\"', 'a;b'),\n                ('foo=\"a\\\\\"b\"', 'a\"b'),\n                ]\n        for header, expected in data:\n            logging.debug(\"trying %r\", header)\n            response = self.fetch(\"/get\", headers={\"Cookie\": header})\n            self.assertEqual(response.body, utf8(expected))\n\n    def test_set_cookie_overwrite(self):\n        response = self.fetch(\"/set_overwrite\")\n        headers = response.headers.get_list(\"Set-Cookie\")\n        self.assertEqual(sorted(headers),\n                         [\"a=e; Path=/\", \"c=d; Domain=example.com; Path=/\"])\n\n\nclass AuthRedirectRequestHandler(RequestHandler):\n    def initialize(self, login_url):\n        self.login_url = login_url\n\n    def get_login_url(self):\n        return self.login_url\n\n    @authenticated\n    def get(self):\n        # we'll never actually get here because the test doesn't follow redirects\n        self.send_error(500)\n\n\nclass AuthRedirectTest(WebTestCase):\n    def get_handlers(self):\n        return [('/relative', AuthRedirectRequestHandler,\n                 dict(login_url='/login')),\n                ('/absolute', AuthRedirectRequestHandler,\n                 dict(login_url='http://example.com/login'))]\n\n    def test_relative_auth_redirect(self):\n        self.http_client.fetch(self.get_url('/relative'), self.stop,\n                               follow_redirects=False)\n        response = self.wait()\n        self.assertEqual(response.code, 302)\n        self.assertEqual(response.headers['Location'], '/login?next=%2Frelative')\n\n    def test_absolute_auth_redirect(self):\n        self.http_client.fetch(self.get_url('/absolute'), self.stop,\n                               follow_redirects=False)\n        response = self.wait()\n        self.assertEqual(response.code, 302)\n        self.assertTrue(re.match(\n            'http://example.com/login\\?next=http%3A%2F%2Flocalhost%3A[0-9]+%2Fabsolute',\n            response.headers['Location']), response.headers['Location'])\n\n\nclass ConnectionCloseHandler(RequestHandler):\n    def initialize(self, test):\n        self.test = test\n\n    @asynchronous\n    def get(self):\n        self.test.on_handler_waiting()\n\n    def on_connection_close(self):\n        self.test.on_connection_close()\n\n\nclass ConnectionCloseTest(WebTestCase):\n    def get_handlers(self):\n        return [('/', ConnectionCloseHandler, dict(test=self))]\n\n    def test_connection_close(self):\n        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)\n        s.connect((\"localhost\", self.get_http_port()))\n        self.stream = IOStream(s, io_loop=self.io_loop)\n        self.stream.write(b\"GET / HTTP/1.0\\r\\n\\r\\n\")\n        self.wait()\n\n    def on_handler_waiting(self):\n        logging.debug('handler waiting')\n        self.stream.close()\n\n    def on_connection_close(self):\n        logging.debug('connection closed')\n        self.stop()\n\n\nclass EchoHandler(RequestHandler):\n    def get(self, *path_args):\n        # Type checks: web.py interfaces convert argument values to\n        # unicode strings (by default, but see also decode_argument).\n        # In httpserver.py (i.e. self.request.arguments), they're left\n        # as bytes.  Keys are always native strings.\n        for key in self.request.arguments:\n            if type(key) != str:\n                raise Exception(\"incorrect type for key: %r\" % type(key))\n            for value in self.request.arguments[key]:\n                if type(value) != bytes_type:\n                    raise Exception(\"incorrect type for value: %r\" %\n                                    type(value))\n            for value in self.get_arguments(key):\n                if type(value) != unicode_type:\n                    raise Exception(\"incorrect type for value: %r\" %\n                                    type(value))\n        for arg in path_args:\n            if type(arg) != unicode_type:\n                raise Exception(\"incorrect type for path arg: %r\" % type(arg))\n        self.write(dict(path=self.request.path,\n                        path_args=path_args,\n                        args=recursive_unicode(self.request.arguments)))\n\n\nclass RequestEncodingTest(WebTestCase):\n    def get_handlers(self):\n        return [(\"/group/(.*)\", EchoHandler),\n                (\"/slashes/([^/]*)/([^/]*)\", EchoHandler),\n                ]\n\n    def fetch_json(self, path):\n        return json_decode(self.fetch(path).body)\n\n    def test_group_question_mark(self):\n        # Ensure that url-encoded question marks are handled properly\n        self.assertEqual(self.fetch_json('/group/%3F'),\n                         dict(path='/group/%3F', path_args=['?'], args={}))\n        self.assertEqual(self.fetch_json('/group/%3F?%3F=%3F'),\n                         dict(path='/group/%3F', path_args=['?'], args={'?': ['?']}))\n\n    def test_group_encoding(self):\n        # Path components and query arguments should be decoded the same way\n        self.assertEqual(self.fetch_json('/group/%C3%A9?arg=%C3%A9'),\n                         {u(\"path\"): u(\"/group/%C3%A9\"),\n                          u(\"path_args\"): [u(\"\\u00e9\")],\n                          u(\"args\"): {u(\"arg\"): [u(\"\\u00e9\")]}})\n\n    def test_slashes(self):\n        # Slashes may be escaped to appear as a single \"directory\" in the path,\n        # but they are then unescaped when passed to the get() method.\n        self.assertEqual(self.fetch_json('/slashes/foo/bar'),\n                         dict(path=\"/slashes/foo/bar\",\n                              path_args=[\"foo\", \"bar\"],\n                              args={}))\n        self.assertEqual(self.fetch_json('/slashes/a%2Fb/c%2Fd'),\n                         dict(path=\"/slashes/a%2Fb/c%2Fd\",\n                              path_args=[\"a/b\", \"c/d\"],\n                              args={}))\n\n\nclass TypeCheckHandler(RequestHandler):\n    def prepare(self):\n        self.errors = {}\n\n        self.check_type('status', self.get_status(), int)\n\n        # get_argument is an exception from the general rule of using\n        # type str for non-body data mainly for historical reasons.\n        self.check_type('argument', self.get_argument('foo'), unicode_type)\n        self.check_type('cookie_key', list(self.cookies.keys())[0], str)\n        self.check_type('cookie_value', list(self.cookies.values())[0].value, str)\n\n        # Secure cookies return bytes because they can contain arbitrary\n        # data, but regular cookies are native strings.\n        if list(self.cookies.keys()) != ['asdf']:\n            raise Exception(\"unexpected values for cookie keys: %r\" %\n                            self.cookies.keys())\n        self.check_type('get_secure_cookie', self.get_secure_cookie('asdf'), bytes_type)\n        self.check_type('get_cookie', self.get_cookie('asdf'), str)\n\n        self.check_type('xsrf_token', self.xsrf_token, bytes_type)\n        self.check_type('xsrf_form_html', self.xsrf_form_html(), str)\n\n        self.check_type('reverse_url', self.reverse_url('typecheck', 'foo'), str)\n\n        self.check_type('request_summary', self._request_summary(), str)\n\n    def get(self, path_component):\n        # path_component uses type unicode instead of str for consistency\n        # with get_argument()\n        self.check_type('path_component', path_component, unicode_type)\n        self.write(self.errors)\n\n    def post(self, path_component):\n        self.check_type('path_component', path_component, unicode_type)\n        self.write(self.errors)\n\n    def check_type(self, name, obj, expected_type):\n        actual_type = type(obj)\n        if expected_type != actual_type:\n            self.errors[name] = \"expected %s, got %s\" % (expected_type,\n                                                         actual_type)\n\n\nclass DecodeArgHandler(RequestHandler):\n    def decode_argument(self, value, name=None):\n        if type(value) != bytes_type:\n            raise Exception(\"unexpected type for value: %r\" % type(value))\n        # use self.request.arguments directly to avoid recursion\n        if 'encoding' in self.request.arguments:\n            return value.decode(to_unicode(self.request.arguments['encoding'][0]))\n        else:\n            return value\n\n    def get(self, arg):\n        def describe(s):\n            if type(s) == bytes_type:\n                return [\"bytes\", native_str(binascii.b2a_hex(s))]\n            elif type(s) == unicode_type:\n                return [\"unicode\", s]\n            raise Exception(\"unknown type\")\n        self.write({'path': describe(arg),\n                    'query': describe(self.get_argument(\"foo\")),\n                    })\n\n\nclass LinkifyHandler(RequestHandler):\n    def get(self):\n        self.render(\"linkify.html\", message=\"http://example.com\")\n\n\nclass UIModuleResourceHandler(RequestHandler):\n    def get(self):\n        self.render(\"page.html\", entries=[1, 2])\n\n\nclass OptionalPathHandler(RequestHandler):\n    def get(self, path):\n        self.write({\"path\": path})\n\n\nclass FlowControlHandler(RequestHandler):\n    # These writes are too small to demonstrate real flow control,\n    # but at least it shows that the callbacks get run.\n    @asynchronous\n    def get(self):\n        self.write(\"1\")\n        self.flush(callback=self.step2)\n\n    def step2(self):\n        self.write(\"2\")\n        self.flush(callback=self.step3)\n\n    def step3(self):\n        self.write(\"3\")\n        self.finish()\n\n\nclass MultiHeaderHandler(RequestHandler):\n    def get(self):\n        self.set_header(\"x-overwrite\", \"1\")\n        self.set_header(\"X-Overwrite\", 2)\n        self.add_header(\"x-multi\", 3)\n        self.add_header(\"X-Multi\", \"4\")\n\n\nclass RedirectHandler(RequestHandler):\n    def get(self):\n        if self.get_argument('permanent', None) is not None:\n            self.redirect('/', permanent=int(self.get_argument('permanent')))\n        elif self.get_argument('status', None) is not None:\n            self.redirect('/', status=int(self.get_argument('status')))\n        else:\n            raise Exception(\"didn't get permanent or status arguments\")\n\n\nclass EmptyFlushCallbackHandler(RequestHandler):\n    @gen.engine\n    @asynchronous\n    def get(self):\n        # Ensure that the flush callback is run whether or not there\n        # was any output.\n        yield gen.Task(self.flush)  # \"empty\" flush, but writes headers\n        yield gen.Task(self.flush)  # empty flush\n        self.write(\"o\")\n        yield gen.Task(self.flush)  # flushes the \"o\"\n        yield gen.Task(self.flush)  # empty flush\n        self.finish(\"k\")\n\n\nclass HeaderInjectionHandler(RequestHandler):\n    def get(self):\n        try:\n            self.set_header(\"X-Foo\", \"foo\\r\\nX-Bar: baz\")\n            raise Exception(\"Didn't get expected exception\")\n        except ValueError as e:\n            if \"Unsafe header value\" in str(e):\n                self.finish(b\"ok\")\n            else:\n                raise\n\n\nclass GetArgumentHandler(RequestHandler):\n    def get(self):\n        self.write(self.get_argument(\"foo\", \"default\"))\n\n\n# This test is shared with wsgi_test.py\n@wsgi_safe\nclass WSGISafeWebTest(WebTestCase):\n    COOKIE_SECRET = \"WebTest.COOKIE_SECRET\"\n\n    def get_app_kwargs(self):\n        loader = DictLoader({\n            \"linkify.html\": \"{% module linkify(message) %}\",\n            \"page.html\": \"\"\"\\\n<html><head></head><body>\n{% for e in entries %}\n{% module Template(\"entry.html\", entry=e) %}\n{% end %}\n</body></html>\"\"\",\n            \"entry.html\": \"\"\"\\\n{{ set_resources(embedded_css=\".entry { margin-bottom: 1em; }\", embedded_javascript=\"js_embed()\", css_files=[\"/base.css\", \"/foo.css\"], javascript_files=\"/common.js\", html_head=\"<meta>\", html_body='<script src=\"/analytics.js\"/>') }}\n<div class=\"entry\">...</div>\"\"\",\n        })\n        return dict(template_loader=loader,\n                    autoescape=\"xhtml_escape\",\n                    cookie_secret=self.COOKIE_SECRET)\n\n    def tearDown(self):\n        super(WSGISafeWebTest, self).tearDown()\n        RequestHandler._template_loaders.clear()\n\n    def get_handlers(self):\n        urls = [\n            url(\"/typecheck/(.*)\", TypeCheckHandler, name='typecheck'),\n            url(\"/decode_arg/(.*)\", DecodeArgHandler, name='decode_arg'),\n            url(\"/decode_arg_kw/(?P<arg>.*)\", DecodeArgHandler),\n            url(\"/linkify\", LinkifyHandler),\n            url(\"/uimodule_resources\", UIModuleResourceHandler),\n            url(\"/optional_path/(.+)?\", OptionalPathHandler),\n            url(\"/multi_header\", MultiHeaderHandler),\n            url(\"/redirect\", RedirectHandler),\n            url(\"/header_injection\", HeaderInjectionHandler),\n            url(\"/get_argument\", GetArgumentHandler),\n        ]\n        return urls\n\n    def fetch_json(self, *args, **kwargs):\n        response = self.fetch(*args, **kwargs)\n        response.rethrow()\n        return json_decode(response.body)\n\n    def test_types(self):\n        cookie_value = to_unicode(create_signed_value(self.COOKIE_SECRET,\n                                                      \"asdf\", \"qwer\"))\n        response = self.fetch(\"/typecheck/asdf?foo=bar\",\n                              headers={\"Cookie\": \"asdf=\" + cookie_value})\n        data = json_decode(response.body)\n        self.assertEqual(data, {})\n\n        response = self.fetch(\"/typecheck/asdf?foo=bar\", method=\"POST\",\n                              headers={\"Cookie\": \"asdf=\" + cookie_value},\n                              body=\"foo=bar\")\n\n    def test_decode_argument(self):\n        # These urls all decode to the same thing\n        urls = [\"/decode_arg/%C3%A9?foo=%C3%A9&encoding=utf-8\",\n                \"/decode_arg/%E9?foo=%E9&encoding=latin1\",\n                \"/decode_arg_kw/%E9?foo=%E9&encoding=latin1\",\n                ]\n        for url in urls:\n            response = self.fetch(url)\n            response.rethrow()\n            data = json_decode(response.body)\n            self.assertEqual(data, {u('path'): [u('unicode'), u('\\u00e9')],\n                                    u('query'): [u('unicode'), u('\\u00e9')],\n                                    })\n\n        response = self.fetch(\"/decode_arg/%C3%A9?foo=%C3%A9\")\n        response.rethrow()\n        data = json_decode(response.body)\n        self.assertEqual(data, {u('path'): [u('bytes'), u('c3a9')],\n                                u('query'): [u('bytes'), u('c3a9')],\n                                })\n\n    def test_decode_argument_plus(self):\n        # These urls are all equivalent.\n        urls = [\"/decode_arg/1%20%2B%201?foo=1%20%2B%201&encoding=utf-8\",\n                \"/decode_arg/1%20+%201?foo=1+%2B+1&encoding=utf-8\"]\n        for url in urls:\n            response = self.fetch(url)\n            response.rethrow()\n            data = json_decode(response.body)\n            self.assertEqual(data, {u('path'): [u('unicode'), u('1 + 1')],\n                                    u('query'): [u('unicode'), u('1 + 1')],\n                                    })\n\n    def test_reverse_url(self):\n        self.assertEqual(self.app.reverse_url('decode_arg', 'foo'),\n                         '/decode_arg/foo')\n        self.assertEqual(self.app.reverse_url('decode_arg', 42),\n                         '/decode_arg/42')\n        self.assertEqual(self.app.reverse_url('decode_arg', b'\\xe9'),\n                         '/decode_arg/%E9')\n        self.assertEqual(self.app.reverse_url('decode_arg', u('\\u00e9')),\n                         '/decode_arg/%C3%A9')\n        self.assertEqual(self.app.reverse_url('decode_arg', '1 + 1'),\n                         '/decode_arg/1%20%2B%201')\n\n    def test_uimodule_unescaped(self):\n        response = self.fetch(\"/linkify\")\n        self.assertEqual(response.body,\n                         b\"<a href=\\\"http://example.com\\\">http://example.com</a>\")\n\n    def test_uimodule_resources(self):\n        response = self.fetch(\"/uimodule_resources\")\n        self.assertEqual(response.body, b\"\"\"\\\n<html><head><link href=\"/base.css\" type=\"text/css\" rel=\"stylesheet\"/><link href=\"/foo.css\" type=\"text/css\" rel=\"stylesheet\"/>\n<style type=\"text/css\">\n.entry { margin-bottom: 1em; }\n</style>\n<meta>\n</head><body>\n\n\n<div class=\"entry\">...</div>\n\n\n<div class=\"entry\">...</div>\n\n<script src=\"/common.js\" type=\"text/javascript\"></script>\n<script type=\"text/javascript\">\n//<![CDATA[\njs_embed()\n//]]>\n</script>\n<script src=\"/analytics.js\"/>\n</body></html>\"\"\")\n\n    def test_optional_path(self):\n        self.assertEqual(self.fetch_json(\"/optional_path/foo\"),\n                         {u(\"path\"): u(\"foo\")})\n        self.assertEqual(self.fetch_json(\"/optional_path/\"),\n                         {u(\"path\"): None})\n\n    def test_multi_header(self):\n        response = self.fetch(\"/multi_header\")\n        self.assertEqual(response.headers[\"x-overwrite\"], \"2\")\n        self.assertEqual(response.headers.get_list(\"x-multi\"), [\"3\", \"4\"])\n\n    def test_redirect(self):\n        response = self.fetch(\"/redirect?permanent=1\", follow_redirects=False)\n        self.assertEqual(response.code, 301)\n        response = self.fetch(\"/redirect?permanent=0\", follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        response = self.fetch(\"/redirect?status=307\", follow_redirects=False)\n        self.assertEqual(response.code, 307)\n\n    def test_header_injection(self):\n        response = self.fetch(\"/header_injection\")\n        self.assertEqual(response.body, b\"ok\")\n\n    def test_get_argument(self):\n        response = self.fetch(\"/get_argument?foo=bar\")\n        self.assertEqual(response.body, b\"bar\")\n        response = self.fetch(\"/get_argument?foo=\")\n        self.assertEqual(response.body, b\"\")\n        response = self.fetch(\"/get_argument\")\n        self.assertEqual(response.body, b\"default\")\n\n    def test_no_gzip(self):\n        response = self.fetch('/get_argument')\n        self.assertNotIn('Accept-Encoding', response.headers.get('Vary', ''))\n        self.assertNotIn('gzip', response.headers.get('Content-Encoding', ''))\n\n\nclass NonWSGIWebTests(WebTestCase):\n    def get_handlers(self):\n        return [(\"/flow_control\", FlowControlHandler),\n                (\"/empty_flush\", EmptyFlushCallbackHandler),\n                ]\n\n    def test_flow_control(self):\n        self.assertEqual(self.fetch(\"/flow_control\").body, b\"123\")\n\n    def test_empty_flush(self):\n        response = self.fetch(\"/empty_flush\")\n        self.assertEqual(response.body, b\"ok\")\n\n\n@wsgi_safe\nclass ErrorResponseTest(WebTestCase):\n    def get_handlers(self):\n        class DefaultHandler(RequestHandler):\n            def get(self):\n                if self.get_argument(\"status\", None):\n                    raise HTTPError(int(self.get_argument(\"status\")))\n                1 / 0\n\n        class WriteErrorHandler(RequestHandler):\n            def get(self):\n                if self.get_argument(\"status\", None):\n                    self.send_error(int(self.get_argument(\"status\")))\n                else:\n                    1 / 0\n\n            def write_error(self, status_code, **kwargs):\n                self.set_header(\"Content-Type\", \"text/plain\")\n                if \"exc_info\" in kwargs:\n                    self.write(\"Exception: %s\" % kwargs[\"exc_info\"][0].__name__)\n                else:\n                    self.write(\"Status: %d\" % status_code)\n\n        class GetErrorHtmlHandler(RequestHandler):\n            def get(self):\n                if self.get_argument(\"status\", None):\n                    self.send_error(int(self.get_argument(\"status\")))\n                else:\n                    1 / 0\n\n            def get_error_html(self, status_code, **kwargs):\n                self.set_header(\"Content-Type\", \"text/plain\")\n                if \"exception\" in kwargs:\n                    self.write(\"Exception: %s\" % sys.exc_info()[0].__name__)\n                else:\n                    self.write(\"Status: %d\" % status_code)\n\n        class FailedWriteErrorHandler(RequestHandler):\n            def get(self):\n                1 / 0\n\n            def write_error(self, status_code, **kwargs):\n                raise Exception(\"exception in write_error\")\n\n        return [url(\"/default\", DefaultHandler),\n                url(\"/write_error\", WriteErrorHandler),\n                url(\"/get_error_html\", GetErrorHtmlHandler),\n                url(\"/failed_write_error\", FailedWriteErrorHandler),\n                ]\n\n    def test_default(self):\n        with ExpectLog(app_log, \"Uncaught exception\"):\n            response = self.fetch(\"/default\")\n            self.assertEqual(response.code, 500)\n            self.assertTrue(b\"500: Internal Server Error\" in response.body)\n\n            response = self.fetch(\"/default?status=503\")\n            self.assertEqual(response.code, 503)\n            self.assertTrue(b\"503: Service Unavailable\" in response.body)\n\n    def test_write_error(self):\n        with ExpectLog(app_log, \"Uncaught exception\"):\n            response = self.fetch(\"/write_error\")\n            self.assertEqual(response.code, 500)\n            self.assertEqual(b\"Exception: ZeroDivisionError\", response.body)\n\n            response = self.fetch(\"/write_error?status=503\")\n            self.assertEqual(response.code, 503)\n            self.assertEqual(b\"Status: 503\", response.body)\n\n    def test_get_error_html(self):\n        with ExpectLog(app_log, \"Uncaught exception\"):\n            response = self.fetch(\"/get_error_html\")\n            self.assertEqual(response.code, 500)\n            self.assertEqual(b\"Exception: ZeroDivisionError\", response.body)\n\n            response = self.fetch(\"/get_error_html?status=503\")\n            self.assertEqual(response.code, 503)\n            self.assertEqual(b\"Status: 503\", response.body)\n\n    def test_failed_write_error(self):\n        with ExpectLog(app_log, \"Uncaught exception\"):\n            response = self.fetch(\"/failed_write_error\")\n            self.assertEqual(response.code, 500)\n            self.assertEqual(b\"\", response.body)\n\n\n@wsgi_safe\nclass StaticFileTest(WebTestCase):\n    # The expected MD5 hash of robots.txt, used in tests that call\n    # StaticFileHandler.get_version\n    robots_txt_hash = b\"f71d20196d4caf35b6a670db8c70b03d\"\n    static_dir = os.path.join(os.path.dirname(__file__), 'static')\n\n    def get_handlers(self):\n        class StaticUrlHandler(RequestHandler):\n            def get(self, path):\n                with_v = int(self.get_argument('include_version', 1))\n                self.write(self.static_url(path, include_version=with_v))\n\n        class AbsoluteStaticUrlHandler(StaticUrlHandler):\n            include_host = True\n\n        class OverrideStaticUrlHandler(RequestHandler):\n            def get(self, path):\n                do_include = bool(self.get_argument(\"include_host\"))\n                self.include_host = not do_include\n\n                regular_url = self.static_url(path)\n                override_url = self.static_url(path, include_host=do_include)\n                if override_url == regular_url:\n                    return self.write(str(False))\n\n                protocol = self.request.protocol + \"://\"\n                protocol_length = len(protocol)\n                check_regular = regular_url.find(protocol, 0, protocol_length)\n                check_override = override_url.find(protocol, 0, protocol_length)\n\n                if do_include:\n                    result = (check_override == 0 and check_regular == -1)\n                else:\n                    result = (check_override == -1 and check_regular == 0)\n                self.write(str(result))\n\n        return [('/static_url/(.*)', StaticUrlHandler),\n                ('/abs_static_url/(.*)', AbsoluteStaticUrlHandler),\n                ('/override_static_url/(.*)', OverrideStaticUrlHandler)]\n\n    def get_app_kwargs(self):\n        return dict(static_path=relpath('static'))\n\n    def test_static_files(self):\n        response = self.fetch('/robots.txt')\n        self.assertTrue(b\"Disallow: /\" in response.body)\n\n        response = self.fetch('/static/robots.txt')\n        self.assertTrue(b\"Disallow: /\" in response.body)\n\n    def test_static_url(self):\n        response = self.fetch(\"/static_url/robots.txt\")\n        self.assertEqual(response.body,\n                         b\"/static/robots.txt?v=\" + self.robots_txt_hash)\n\n    def test_absolute_static_url(self):\n        response = self.fetch(\"/abs_static_url/robots.txt\")\n        self.assertEqual(response.body, (\n            utf8(self.get_url(\"/\")) +\n            b\"static/robots.txt?v=\" +\n            self.robots_txt_hash\n        ))\n\n    def test_relative_version_exclusion(self):\n        response = self.fetch(\"/static_url/robots.txt?include_version=0\")\n        self.assertEqual(response.body, b\"/static/robots.txt\")\n\n    def test_absolute_version_exclusion(self):\n        response = self.fetch(\"/abs_static_url/robots.txt?include_version=0\")\n        self.assertEqual(response.body,\n                         utf8(self.get_url(\"/\") + \"static/robots.txt\"))\n\n    def test_include_host_override(self):\n        self._trigger_include_host_check(False)\n        self._trigger_include_host_check(True)\n\n    def _trigger_include_host_check(self, include_host):\n        path = \"/override_static_url/robots.txt?include_host=%s\"\n        response = self.fetch(path % int(include_host))\n        self.assertEqual(response.body, utf8(str(True)))\n\n    def test_static_304_if_modified_since(self):\n        response1 = self.fetch(\"/static/robots.txt\")\n        response2 = self.fetch(\"/static/robots.txt\", headers={\n            'If-Modified-Since': response1.headers['Last-Modified']})\n        self.assertEqual(response2.code, 304)\n        self.assertTrue('Content-Length' not in response2.headers)\n        self.assertTrue('Last-Modified' not in response2.headers)\n\n    def test_static_304_if_none_match(self):\n        response1 = self.fetch(\"/static/robots.txt\")\n        response2 = self.fetch(\"/static/robots.txt\", headers={\n            'If-None-Match': response1.headers['Etag']})\n        self.assertEqual(response2.code, 304)\n\n    def test_static_if_modified_since_pre_epoch(self):\n        # On windows, the functions that work with time_t do not accept\n        # negative values, and at least one client (processing.js) seems\n        # to use if-modified-since 1/1/1960 as a cache-busting technique.\n        response = self.fetch(\"/static/robots.txt\", headers={\n            'If-Modified-Since': 'Fri, 01 Jan 1960 00:00:00 GMT'})\n        self.assertEqual(response.code, 200)\n\n    def test_static_if_modified_since_time_zone(self):\n        # Instead of the value from Last-Modified, make requests with times\n        # chosen just before and after the known modification time\n        # of the file to ensure that the right time zone is being used\n        # when parsing If-Modified-Since.\n        stat = os.stat(relpath('static/robots.txt'))\n\n        response = self.fetch('/static/robots.txt', headers={\n            'If-Modified-Since': format_timestamp(stat.st_mtime - 1)})\n        self.assertEqual(response.code, 200)\n        response = self.fetch('/static/robots.txt', headers={\n            'If-Modified-Since': format_timestamp(stat.st_mtime + 1)})\n        self.assertEqual(response.code, 304)\n\n    def test_static_etag(self):\n        response = self.fetch('/static/robots.txt')\n        self.assertEqual(utf8(response.headers.get(\"Etag\")),\n                         b'\"' + self.robots_txt_hash + b'\"')\n\n    def test_static_with_range(self):\n        response = self.fetch('/static/robots.txt', headers={\n            'Range': 'bytes=0-9'})\n        self.assertEqual(response.code, 206)\n        self.assertEqual(response.body, b\"User-agent\")\n        self.assertEqual(utf8(response.headers.get(\"Etag\")),\n                         b'\"' + self.robots_txt_hash + b'\"')\n        self.assertEqual(response.headers.get(\"Content-Length\"), \"10\")\n        self.assertEqual(response.headers.get(\"Content-Range\"),\n                         \"bytes 0-9/26\")\n\n    def test_static_with_range_full_file(self):\n        response = self.fetch('/static/robots.txt', headers={\n            'Range': 'bytes=0-'})\n        # Note: Chrome refuses to play audio if it gets an HTTP 206 in response\n        # to ``Range: bytes=0-`` :(\n        self.assertEqual(response.code, 200)\n        robots_file_path = os.path.join(self.static_dir, \"robots.txt\")\n        with open(robots_file_path) as f:\n            self.assertEqual(response.body, utf8(f.read()))\n        self.assertEqual(response.headers.get(\"Content-Length\"), \"26\")\n        self.assertEqual(response.headers.get(\"Content-Range\"), None)\n\n    def test_static_with_range_full_past_end(self):\n        response = self.fetch('/static/robots.txt', headers={\n            'Range': 'bytes=0-10000000'})\n        self.assertEqual(response.code, 200)\n        robots_file_path = os.path.join(self.static_dir, \"robots.txt\")\n        with open(robots_file_path) as f:\n            self.assertEqual(response.body, utf8(f.read()))\n        self.assertEqual(response.headers.get(\"Content-Length\"), \"26\")\n        self.assertEqual(response.headers.get(\"Content-Range\"), None)\n\n    def test_static_with_range_partial_past_end(self):\n        response = self.fetch('/static/robots.txt', headers={\n            'Range': 'bytes=1-10000000'})\n        self.assertEqual(response.code, 206)\n        robots_file_path = os.path.join(self.static_dir, \"robots.txt\")\n        with open(robots_file_path) as f:\n            self.assertEqual(response.body, utf8(f.read()[1:]))\n        self.assertEqual(response.headers.get(\"Content-Length\"), \"25\")\n        self.assertEqual(response.headers.get(\"Content-Range\"), \"bytes 1-25/26\")\n\n    def test_static_with_range_end_edge(self):\n        response = self.fetch('/static/robots.txt', headers={\n            'Range': 'bytes=22-'})\n        self.assertEqual(response.body, b\": /\\n\")\n        self.assertEqual(response.headers.get(\"Content-Length\"), \"4\")\n        self.assertEqual(response.headers.get(\"Content-Range\"),\n                         \"bytes 22-25/26\")\n\n    def test_static_with_range_neg_end(self):\n        response = self.fetch('/static/robots.txt', headers={\n            'Range': 'bytes=-4'})\n        self.assertEqual(response.body, b\": /\\n\")\n        self.assertEqual(response.headers.get(\"Content-Length\"), \"4\")\n        self.assertEqual(response.headers.get(\"Content-Range\"),\n                         \"bytes 22-25/26\")\n\n    def test_static_invalid_range(self):\n        response = self.fetch('/static/robots.txt', headers={\n            'Range': 'asdf'})\n        self.assertEqual(response.code, 200)\n\n    def test_static_unsatisfiable_range_zero_suffix(self):\n        response = self.fetch('/static/robots.txt', headers={\n            'Range': 'bytes=-0'})\n        self.assertEqual(response.headers.get(\"Content-Range\"),\n                         \"bytes */26\")\n        self.assertEqual(response.code, 416)\n\n    def test_static_unsatisfiable_range_invalid_start(self):\n        response = self.fetch('/static/robots.txt', headers={\n            'Range': 'bytes=26'})\n        self.assertEqual(response.code, 416)\n        self.assertEqual(response.headers.get(\"Content-Range\"),\n                         \"bytes */26\")\n\n    def test_static_head(self):\n        response = self.fetch('/static/robots.txt', method='HEAD')\n        self.assertEqual(response.code, 200)\n        # No body was returned, but we did get the right content length.\n        self.assertEqual(response.body, b'')\n        self.assertEqual(response.headers['Content-Length'], '26')\n        self.assertEqual(utf8(response.headers['Etag']),\n                         b'\"' + self.robots_txt_hash + b'\"')\n\n    def test_static_head_range(self):\n        response = self.fetch('/static/robots.txt', method='HEAD',\n                              headers={'Range': 'bytes=1-4'})\n        self.assertEqual(response.code, 206)\n        self.assertEqual(response.body, b'')\n        self.assertEqual(response.headers['Content-Length'], '4')\n        self.assertEqual(utf8(response.headers['Etag']),\n                         b'\"' + self.robots_txt_hash + b'\"')\n\n    def test_static_range_if_none_match(self):\n        response = self.fetch('/static/robots.txt', headers={\n            'Range': 'bytes=1-4',\n            'If-None-Match': b'\"' + self.robots_txt_hash + b'\"'})\n        self.assertEqual(response.code, 304)\n        self.assertEqual(response.body, b'')\n        self.assertTrue('Content-Length' not in response.headers)\n        self.assertEqual(utf8(response.headers['Etag']),\n                         b'\"' + self.robots_txt_hash + b'\"')\n\n    def test_static_404(self):\n        response = self.fetch('/static/blarg')\n        self.assertEqual(response.code, 404)\n\n\n@wsgi_safe\nclass StaticDefaultFilenameTest(WebTestCase):\n    def get_app_kwargs(self):\n        return dict(static_path=relpath('static'),\n                    static_handler_args=dict(default_filename='index.html'))\n\n    def get_handlers(self):\n        return []\n\n    def test_static_default_filename(self):\n        response = self.fetch('/static/dir/', follow_redirects=False)\n        self.assertEqual(response.code, 200)\n        self.assertEqual(b'this is the index\\n', response.body)\n\n    def test_static_default_redirect(self):\n        response = self.fetch('/static/dir', follow_redirects=False)\n        self.assertEqual(response.code, 301)\n        self.assertTrue(response.headers['Location'].endswith('/static/dir/'))\n\n\n@wsgi_safe\nclass StaticFileWithPathTest(WebTestCase):\n    def get_app_kwargs(self):\n        return dict(static_path=relpath('static'),\n                    static_handler_args=dict(default_filename='index.html'))\n\n    def get_handlers(self):\n        return [(\"/foo/(.*)\", StaticFileHandler, {\n            \"path\": relpath(\"templates/\"),\n        })]\n\n    def test_serve(self):\n        response = self.fetch(\"/foo/utf8.html\")\n        self.assertEqual(response.body, b\"H\\xc3\\xa9llo\\n\")\n\n\n@wsgi_safe\nclass CustomStaticFileTest(WebTestCase):\n    def get_handlers(self):\n        class MyStaticFileHandler(StaticFileHandler):\n            @classmethod\n            def make_static_url(cls, settings, path):\n                version_hash = cls.get_version(settings, path)\n                extension_index = path.rindex('.')\n                before_version = path[:extension_index]\n                after_version = path[(extension_index + 1):]\n                return '/static/%s.%s.%s' % (before_version, version_hash,\n                                             after_version)\n\n            def parse_url_path(self, url_path):\n                extension_index = url_path.rindex('.')\n                version_index = url_path.rindex('.', 0, extension_index)\n                return '%s%s' % (url_path[:version_index],\n                                 url_path[extension_index:])\n\n            @classmethod\n            def get_absolute_path(cls, settings, path):\n                return 'CustomStaticFileTest:' + path\n\n            def validate_absolute_path(self, root, absolute_path):\n                return absolute_path\n\n            @classmethod\n            def get_content(self, path, start=None, end=None):\n                assert start is None and end is None\n                if path == 'CustomStaticFileTest:foo.txt':\n                    return b'bar'\n                raise Exception(\"unexpected path %r\" % path)\n\n            def get_modified_time(self):\n                return None\n\n            @classmethod\n            def get_version(cls, settings, path):\n                return \"42\"\n\n        class StaticUrlHandler(RequestHandler):\n            def get(self, path):\n                self.write(self.static_url(path))\n\n        self.static_handler_class = MyStaticFileHandler\n\n        return [(\"/static_url/(.*)\", StaticUrlHandler)]\n\n    def get_app_kwargs(self):\n        return dict(static_path=\"dummy\",\n                    static_handler_class=self.static_handler_class)\n\n    def test_serve(self):\n        response = self.fetch(\"/static/foo.42.txt\")\n        self.assertEqual(response.body, b\"bar\")\n\n    def test_static_url(self):\n        with ExpectLog(gen_log, \"Could not open static file\", required=False):\n            response = self.fetch(\"/static_url/foo.txt\")\n            self.assertEqual(response.body, b\"/static/foo.42.txt\")\n\n\n@wsgi_safe\nclass HostMatchingTest(WebTestCase):\n    class Handler(RequestHandler):\n        def initialize(self, reply):\n            self.reply = reply\n\n        def get(self):\n            self.write(self.reply)\n\n    def get_handlers(self):\n        return [(\"/foo\", HostMatchingTest.Handler, {\"reply\": \"wildcard\"})]\n\n    def test_host_matching(self):\n        self.app.add_handlers(\"www.example.com\",\n                              [(\"/foo\", HostMatchingTest.Handler, {\"reply\": \"[0]\"})])\n        self.app.add_handlers(r\"www\\.example\\.com\",\n                              [(\"/bar\", HostMatchingTest.Handler, {\"reply\": \"[1]\"})])\n        self.app.add_handlers(\"www.example.com\",\n                              [(\"/baz\", HostMatchingTest.Handler, {\"reply\": \"[2]\"})])\n\n        response = self.fetch(\"/foo\")\n        self.assertEqual(response.body, b\"wildcard\")\n        response = self.fetch(\"/bar\")\n        self.assertEqual(response.code, 404)\n        response = self.fetch(\"/baz\")\n        self.assertEqual(response.code, 404)\n\n        response = self.fetch(\"/foo\", headers={'Host': 'www.example.com'})\n        self.assertEqual(response.body, b\"[0]\")\n        response = self.fetch(\"/bar\", headers={'Host': 'www.example.com'})\n        self.assertEqual(response.body, b\"[1]\")\n        response = self.fetch(\"/baz\", headers={'Host': 'www.example.com'})\n        self.assertEqual(response.body, b\"[2]\")\n\n\n@wsgi_safe\nclass NamedURLSpecGroupsTest(WebTestCase):\n    def get_handlers(self):\n        class EchoHandler(RequestHandler):\n            def get(self, path):\n                self.write(path)\n\n        return [(\"/str/(?P<path>.*)\", EchoHandler),\n                (u(\"/unicode/(?P<path>.*)\"), EchoHandler)]\n\n    def test_named_urlspec_groups(self):\n        response = self.fetch(\"/str/foo\")\n        self.assertEqual(response.body, b\"foo\")\n\n        response = self.fetch(\"/unicode/bar\")\n        self.assertEqual(response.body, b\"bar\")\n\n\n@wsgi_safe\nclass ClearHeaderTest(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        def get(self):\n            self.set_header(\"h1\", \"foo\")\n            self.set_header(\"h2\", \"bar\")\n            self.clear_header(\"h1\")\n            self.clear_header(\"nonexistent\")\n\n    def test_clear_header(self):\n        response = self.fetch(\"/\")\n        self.assertTrue(\"h1\" not in response.headers)\n        self.assertEqual(response.headers[\"h2\"], \"bar\")\n\n\n@wsgi_safe\nclass Header304Test(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        def get(self):\n            self.set_header(\"Content-Language\", \"en_US\")\n            self.write(\"hello\")\n\n    def test_304_headers(self):\n        response1 = self.fetch('/')\n        self.assertEqual(response1.headers[\"Content-Length\"], \"5\")\n        self.assertEqual(response1.headers[\"Content-Language\"], \"en_US\")\n\n        response2 = self.fetch('/', headers={\n            'If-None-Match': response1.headers[\"Etag\"]})\n        self.assertEqual(response2.code, 304)\n        self.assertTrue(\"Content-Length\" not in response2.headers)\n        self.assertTrue(\"Content-Language\" not in response2.headers)\n        # Not an entity header, but should not be added to 304s by chunking\n        self.assertTrue(\"Transfer-Encoding\" not in response2.headers)\n\n\n@wsgi_safe\nclass StatusReasonTest(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        def get(self):\n            reason = self.request.arguments.get('reason', [])\n            self.set_status(int(self.get_argument('code')),\n                            reason=reason[0] if reason else None)\n\n    def get_http_client(self):\n        # simple_httpclient only: curl doesn't expose the reason string\n        return SimpleAsyncHTTPClient(io_loop=self.io_loop)\n\n    def test_status(self):\n        response = self.fetch(\"/?code=304\")\n        self.assertEqual(response.code, 304)\n        self.assertEqual(response.reason, \"Not Modified\")\n        response = self.fetch(\"/?code=304&reason=Foo\")\n        self.assertEqual(response.code, 304)\n        self.assertEqual(response.reason, \"Foo\")\n        response = self.fetch(\"/?code=682&reason=Bar\")\n        self.assertEqual(response.code, 682)\n        self.assertEqual(response.reason, \"Bar\")\n        with ExpectLog(app_log, 'Uncaught exception'):\n            response = self.fetch(\"/?code=682\")\n        self.assertEqual(response.code, 500)\n\n\n@wsgi_safe\nclass DateHeaderTest(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        def get(self):\n            self.write(\"hello\")\n\n    def test_date_header(self):\n        response = self.fetch('/')\n        header_date = datetime.datetime(\n            *email.utils.parsedate(response.headers['Date'])[:6])\n        self.assertTrue(header_date - datetime.datetime.utcnow() <\n                        datetime.timedelta(seconds=2))\n\n\n@wsgi_safe\nclass RaiseWithReasonTest(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        def get(self):\n            raise HTTPError(682, reason=\"Foo\")\n\n    def get_http_client(self):\n        # simple_httpclient only: curl doesn't expose the reason string\n        return SimpleAsyncHTTPClient(io_loop=self.io_loop)\n\n    def test_raise_with_reason(self):\n        response = self.fetch(\"/\")\n        self.assertEqual(response.code, 682)\n        self.assertEqual(response.reason, \"Foo\")\n        self.assertIn(b'682: Foo', response.body)\n\n    def test_httperror_str(self):\n        self.assertEqual(str(HTTPError(682, reason=\"Foo\")), \"HTTP 682: Foo\")\n\n\n@wsgi_safe\nclass ErrorHandlerXSRFTest(WebTestCase):\n    def get_handlers(self):\n        # note that if the handlers list is empty we get the default_host\n        # redirect fallback instead of a 404, so test with both an\n        # explicitly defined error handler and an implicit 404.\n        return [('/error', ErrorHandler, dict(status_code=417))]\n\n    def get_app_kwargs(self):\n        return dict(xsrf_cookies=True)\n\n    def test_error_xsrf(self):\n        response = self.fetch('/error', method='POST', body='')\n        self.assertEqual(response.code, 417)\n\n    def test_404_xsrf(self):\n        response = self.fetch('/404', method='POST', body='')\n        self.assertEqual(response.code, 404)\n\n\nclass GzipTestCase(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        def get(self):\n            if self.get_argument('vary', None):\n                self.set_header('Vary', self.get_argument('vary'))\n            self.write('hello world')\n\n    def get_app_kwargs(self):\n        return dict(gzip=True)\n\n    def test_gzip(self):\n        response = self.fetch('/')\n        self.assertEqual(response.headers['Content-Encoding'], 'gzip')\n        self.assertEqual(response.headers['Vary'], 'Accept-Encoding')\n\n    def test_gzip_not_requested(self):\n        response = self.fetch('/', use_gzip=False)\n        self.assertNotIn('Content-Encoding', response.headers)\n        self.assertEqual(response.headers['Vary'], 'Accept-Encoding')\n\n    def test_vary_already_present(self):\n        response = self.fetch('/?vary=Accept-Language')\n        self.assertEqual(response.headers['Vary'],\n                         'Accept-Language, Accept-Encoding')\n\n\n@wsgi_safe\nclass PathArgsInPrepareTest(WebTestCase):\n    class Handler(RequestHandler):\n        def prepare(self):\n            self.write(dict(args=self.path_args, kwargs=self.path_kwargs))\n\n        def get(self, path):\n            assert path == 'foo'\n            self.finish()\n\n    def get_handlers(self):\n        return [('/pos/(.*)', self.Handler),\n                ('/kw/(?P<path>.*)', self.Handler)]\n\n    def test_pos(self):\n        response = self.fetch('/pos/foo')\n        response.rethrow()\n        data = json_decode(response.body)\n        self.assertEqual(data, {'args': ['foo'], 'kwargs': {}})\n\n    def test_kw(self):\n        response = self.fetch('/kw/foo')\n        response.rethrow()\n        data = json_decode(response.body)\n        self.assertEqual(data, {'args': [], 'kwargs': {'path': 'foo'}})\n\n\n@wsgi_safe\nclass ClearAllCookiesTest(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        def get(self):\n            self.clear_all_cookies()\n            self.write('ok')\n\n    def test_clear_all_cookies(self):\n        response = self.fetch('/', headers={'Cookie': 'foo=bar; baz=xyzzy'})\n        set_cookies = sorted(response.headers.get_list('Set-Cookie'))\n        self.assertTrue(set_cookies[0].startswith('baz=;'))\n        self.assertTrue(set_cookies[1].startswith('foo=;'))\n\n\nclass PermissionError(Exception):\n    pass\n\n\n@wsgi_safe\nclass ExceptionHandlerTest(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        def get(self):\n            exc = self.get_argument('exc')\n            if exc == 'http':\n                raise HTTPError(410, \"no longer here\")\n            elif exc == 'zero':\n                1 / 0\n            elif exc == 'permission':\n                raise PermissionError('not allowed')\n\n        def write_error(self, status_code, **kwargs):\n            if 'exc_info' in kwargs:\n                typ, value, tb = kwargs['exc_info']\n                if isinstance(value, PermissionError):\n                    self.set_status(403)\n                    self.write('PermissionError')\n                    return\n            RequestHandler.write_error(self, status_code, **kwargs)\n\n        def log_exception(self, typ, value, tb):\n            if isinstance(value, PermissionError):\n                app_log.warning('custom logging for PermissionError: %s',\n                                value.args[0])\n            else:\n                RequestHandler.log_exception(self, typ, value, tb)\n\n    def test_http_error(self):\n        # HTTPErrors are logged as warnings with no stack trace.\n        # TODO: extend ExpectLog to test this more precisely\n        with ExpectLog(gen_log, '.*no longer here'):\n            response = self.fetch('/?exc=http')\n            self.assertEqual(response.code, 410)\n\n    def test_unknown_error(self):\n        # Unknown errors are logged as errors with a stack trace.\n        with ExpectLog(app_log, 'Uncaught exception'):\n            response = self.fetch('/?exc=zero')\n            self.assertEqual(response.code, 500)\n\n    def test_known_error(self):\n        # log_exception can override logging behavior, and write_error\n        # can override the response.\n        with ExpectLog(app_log,\n                       'custom logging for PermissionError: not allowed'):\n            response = self.fetch('/?exc=permission')\n            self.assertEqual(response.code, 403)\n\n\n@wsgi_safe\nclass UIMethodUIModuleTest(SimpleHandlerTestCase):\n    \"\"\"Test that UI methods and modules are created correctly and\n    associated with the handler.\n    \"\"\"\n    class Handler(RequestHandler):\n        def get(self):\n            self.render('foo.html')\n\n        def value(self):\n            return self.get_argument(\"value\")\n\n    def get_app_kwargs(self):\n        def my_ui_method(handler, x):\n            return \"In my_ui_method(%s) with handler value %s.\" % (\n                x, handler.value())\n        class MyModule(UIModule):\n            def render(self, x):\n                return \"In MyModule(%s) with handler value %s.\" % (\n                    x, self.handler.value())\n\n        loader = DictLoader({\n            'foo.html': '{{ my_ui_method(42) }} {% module MyModule(123) %}',\n        })\n        return dict(template_loader=loader,\n                    ui_methods={'my_ui_method': my_ui_method},\n                    ui_modules={'MyModule': MyModule})\n\n    def tearDown(self):\n        super(UIMethodUIModuleTest, self).tearDown()\n        # TODO: fix template loader caching so this isn't necessary.\n        RequestHandler._template_loaders.clear()\n\n    def test_ui_method(self):\n        response = self.fetch('/?value=asdf')\n        self.assertEqual(response.body,\n                         b'In my_ui_method(42) with handler value asdf. '\n                         b'In MyModule(123) with handler value asdf.')\n\n\n@wsgi_safe\nclass GetArgumentErrorTest(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        def get(self):\n            try:\n                self.get_argument('foo')\n                self.write({})\n            except MissingArgumentError as e:\n                self.write({'arg_name': e.arg_name,\n                            'log_message': e.log_message})\n\n    def test_catch_error(self):\n        response = self.fetch('/')\n        self.assertEqual(json_decode(response.body),\n                         {'arg_name': 'foo',\n                          'log_message': 'Missing argument foo'})\n\n\nclass MultipleExceptionTest(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        exc_count = 0\n\n        @asynchronous\n        def get(self):\n            from tornado.ioloop import IOLoop\n            IOLoop.current().add_callback(lambda: 1 / 0)\n            IOLoop.current().add_callback(lambda: 1 / 0)\n\n        def log_exception(self, typ, value, tb):\n            MultipleExceptionTest.Handler.exc_count += 1\n\n    def test_multi_exception(self):\n        # This test verifies that multiple exceptions raised into the same\n        # ExceptionStackContext do not generate extraneous log entries\n        # due to \"Cannot send error response after headers written\".\n        # log_exception is called, but it does not proceed to send_error.\n        response = self.fetch('/')\n        self.assertEqual(response.code, 500)\n        response = self.fetch('/')\n        self.assertEqual(response.code, 500)\n        # Each of our two requests generated two exceptions, we should have\n        # seen at least three of them by now (the fourth may still be\n        # in the queue).\n        self.assertGreater(MultipleExceptionTest.Handler.exc_count, 2)\n\n\n@wsgi_safe\nclass SetCurrentUserTest(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        def prepare(self):\n            self.current_user = 'Ben'\n\n        def get(self):\n            self.write('Hello %s' % self.current_user)\n\n    def test_set_current_user(self):\n        # Ensure that current_user can be assigned to normally for apps\n        # that want to forgo the lazy get_current_user property\n        response = self.fetch('/')\n        self.assertEqual(response.body, b'Hello Ben')\n\n\n@wsgi_safe\nclass GetCurrentUserTest(WebTestCase):\n    def get_app_kwargs(self):\n        class WithoutUserModule(UIModule):\n            def render(self):\n                return ''\n\n        class WithUserModule(UIModule):\n            def render(self):\n                return str(self.current_user)\n\n        loader = DictLoader({\n            'without_user.html': '',\n            'with_user.html': '{{ current_user }}',\n            'without_user_module.html': '{% module WithoutUserModule() %}',\n            'with_user_module.html': '{% module WithUserModule() %}',\n        })\n        return dict(template_loader=loader,\n                    ui_modules={'WithUserModule': WithUserModule,\n                                'WithoutUserModule': WithoutUserModule})\n\n    def tearDown(self):\n        super(GetCurrentUserTest, self).tearDown()\n        RequestHandler._template_loaders.clear()\n\n    def get_handlers(self):\n        class CurrentUserHandler(RequestHandler):\n            def prepare(self):\n                self.has_loaded_current_user = False\n\n            def get_current_user(self):\n                self.has_loaded_current_user = True\n                return ''\n\n        class WithoutUserHandler(CurrentUserHandler):\n            def get(self):\n                self.render_string('without_user.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class WithUserHandler(CurrentUserHandler):\n            def get(self):\n                self.render_string('with_user.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class CurrentUserModuleHandler(CurrentUserHandler):\n            def get_template_namespace(self):\n                # If RequestHandler.get_template_namespace is called, then\n                # get_current_user is evaluated. Until #820 is fixed, this\n                # is a small hack to circumvent the issue.\n                return self.ui\n\n        class WithoutUserModuleHandler(CurrentUserModuleHandler):\n            def get(self):\n                self.render_string('without_user_module.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class WithUserModuleHandler(CurrentUserModuleHandler):\n            def get(self):\n                self.render_string('with_user_module.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        return [('/without_user', WithoutUserHandler),\n                ('/with_user', WithUserHandler),\n                ('/without_user_module', WithoutUserModuleHandler),\n                ('/with_user_module', WithUserModuleHandler)]\n\n    @unittest.skip('needs fix')\n    def test_get_current_user_is_lazy(self):\n        # TODO: Make this test pass. See #820.\n        response = self.fetch('/without_user')\n        self.assertEqual(response.body, b'False')\n\n    def test_get_current_user_works(self):\n        response = self.fetch('/with_user')\n        self.assertEqual(response.body, b'True')\n\n    def test_get_current_user_from_ui_module_is_lazy(self):\n        response = self.fetch('/without_user_module')\n        self.assertEqual(response.body, b'False')\n\n    def test_get_current_user_from_ui_module_works(self):\n        response = self.fetch('/with_user_module')\n        self.assertEqual(response.body, b'True')\n\n\n@wsgi_safe\nclass UnimplementedHTTPMethodsTest(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        pass\n\n    def test_unimplemented_standard_methods(self):\n        for method in ['HEAD', 'GET', 'DELETE', 'OPTIONS']:\n            response = self.fetch('/', method=method)\n            self.assertEqual(response.code, 405)\n        for method in ['POST', 'PUT']:\n            response = self.fetch('/', method=method, body=b'')\n            self.assertEqual(response.code, 405)\n\n\nclass UnimplementedNonStandardMethodsTest(SimpleHandlerTestCase):\n    # wsgiref.validate complains about unknown methods in a way that makes\n    # this test not wsgi_safe.\n    class Handler(RequestHandler):\n        def other(self):\n            # Even though this method exists, it won't get called automatically\n            # because it is not in SUPPORTED_METHODS.\n            self.write('other')\n\n    def test_unimplemented_patch(self):\n        # PATCH is recently standardized; Tornado supports it by default\n        # but wsgiref.validate doesn't like it.\n        response = self.fetch('/', method='PATCH', body=b'')\n        self.assertEqual(response.code, 405)\n\n    def test_unimplemented_other(self):\n        response = self.fetch('/', method='OTHER',\n                              allow_nonstandard_methods=True)\n        self.assertEqual(response.code, 405)\n\n\n@wsgi_safe\nclass AllHTTPMethodsTest(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        def method(self):\n            self.write(self.request.method)\n\n        get = delete = options = post = put = method\n\n    def test_standard_methods(self):\n        response = self.fetch('/', method='HEAD')\n        self.assertEqual(response.body, b'')\n        for method in ['GET', 'DELETE', 'OPTIONS']:\n            response = self.fetch('/', method=method)\n            self.assertEqual(response.body, utf8(method))\n        for method in ['POST', 'PUT']:\n            response = self.fetch('/', method=method, body=b'')\n            self.assertEqual(response.body, utf8(method))\n\n\nclass PatchMethodTest(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        SUPPORTED_METHODS = RequestHandler.SUPPORTED_METHODS + ('OTHER',)\n\n        def patch(self):\n            self.write('patch')\n\n        def other(self):\n            self.write('other')\n\n    def test_patch(self):\n        response = self.fetch('/', method='PATCH', body=b'')\n        self.assertEqual(response.body, b'patch')\n\n    def test_other(self):\n        response = self.fetch('/', method='OTHER',\n                              allow_nonstandard_methods=True)\n        self.assertEqual(response.body, b'other')\n\n\n@wsgi_safe\nclass FinishInPrepareTest(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        def prepare(self):\n            self.finish('done')\n\n        def get(self):\n            # It's difficult to assert for certain that a method did not\n            # or will not be called in an asynchronous context, but this\n            # will be logged noisily if it is reached.\n            raise Exception('should not reach this method')\n\n    def test_finish_in_prepare(self):\n        response = self.fetch('/')\n        self.assertEqual(response.body, b'done')\n",
            "header": {
                "file": {
                    "path": "tornado/test/web_test.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "21035c90",
                "new_commit_hash": "3014b663",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tornado/test/web_test.py"
            },
            "plus_file": {
                "path": "b/tornado/test/web_test.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 1479,
                            "length": 6
                        },
                        "new_range": {
                            "start": 1479,
                            "length": 91
                        },
                        "section": "class SetCurrentUserTest(SimpleHandlerTestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        self.assertEqual(response.body, b'Hello Ben')",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "@wsgi_safe",
                                "type": "added"
                            },
                            {
                                "content": "class GetCurrentUserTest(WebTestCase):",
                                "type": "added"
                            },
                            {
                                "content": "    def get_app_kwargs(self):",
                                "type": "added"
                            },
                            {
                                "content": "        class WithoutUserModule(UIModule):",
                                "type": "added"
                            },
                            {
                                "content": "            def render(self):",
                                "type": "added"
                            },
                            {
                                "content": "                return ''",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        class WithUserModule(UIModule):",
                                "type": "added"
                            },
                            {
                                "content": "            def render(self):",
                                "type": "added"
                            },
                            {
                                "content": "                return str(self.current_user)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        loader = DictLoader({",
                                "type": "added"
                            },
                            {
                                "content": "            'without_user.html': '',",
                                "type": "added"
                            },
                            {
                                "content": "            'with_user.html': '{{ current_user }}',",
                                "type": "added"
                            },
                            {
                                "content": "            'without_user_module.html': '{% module WithoutUserModule() %}',",
                                "type": "added"
                            },
                            {
                                "content": "            'with_user_module.html': '{% module WithUserModule() %}',",
                                "type": "added"
                            },
                            {
                                "content": "        })",
                                "type": "added"
                            },
                            {
                                "content": "        return dict(template_loader=loader,",
                                "type": "added"
                            },
                            {
                                "content": "                    ui_modules={'WithUserModule': WithUserModule,",
                                "type": "added"
                            },
                            {
                                "content": "                                'WithoutUserModule': WithoutUserModule})",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def tearDown(self):",
                                "type": "added"
                            },
                            {
                                "content": "        super(GetCurrentUserTest, self).tearDown()",
                                "type": "added"
                            },
                            {
                                "content": "        RequestHandler._template_loaders.clear()",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def get_handlers(self):",
                                "type": "added"
                            },
                            {
                                "content": "        class CurrentUserHandler(RequestHandler):",
                                "type": "added"
                            },
                            {
                                "content": "            def prepare(self):",
                                "type": "added"
                            },
                            {
                                "content": "                self.has_loaded_current_user = False",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "            def get_current_user(self):",
                                "type": "added"
                            },
                            {
                                "content": "                self.has_loaded_current_user = True",
                                "type": "added"
                            },
                            {
                                "content": "                return ''",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        class WithoutUserHandler(CurrentUserHandler):",
                                "type": "added"
                            },
                            {
                                "content": "            def get(self):",
                                "type": "added"
                            },
                            {
                                "content": "                self.render_string('without_user.html')",
                                "type": "added"
                            },
                            {
                                "content": "                self.finish(str(self.has_loaded_current_user))",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        class WithUserHandler(CurrentUserHandler):",
                                "type": "added"
                            },
                            {
                                "content": "            def get(self):",
                                "type": "added"
                            },
                            {
                                "content": "                self.render_string('with_user.html')",
                                "type": "added"
                            },
                            {
                                "content": "                self.finish(str(self.has_loaded_current_user))",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        class CurrentUserModuleHandler(CurrentUserHandler):",
                                "type": "added"
                            },
                            {
                                "content": "            def get_template_namespace(self):",
                                "type": "added"
                            },
                            {
                                "content": "                # If RequestHandler.get_template_namespace is called, then",
                                "type": "added"
                            },
                            {
                                "content": "                # get_current_user is evaluated. Until #820 is fixed, this",
                                "type": "added"
                            },
                            {
                                "content": "                # is a small hack to circumvent the issue.",
                                "type": "added"
                            },
                            {
                                "content": "                return self.ui",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        class WithoutUserModuleHandler(CurrentUserModuleHandler):",
                                "type": "added"
                            },
                            {
                                "content": "            def get(self):",
                                "type": "added"
                            },
                            {
                                "content": "                self.render_string('without_user_module.html')",
                                "type": "added"
                            },
                            {
                                "content": "                self.finish(str(self.has_loaded_current_user))",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        class WithUserModuleHandler(CurrentUserModuleHandler):",
                                "type": "added"
                            },
                            {
                                "content": "            def get(self):",
                                "type": "added"
                            },
                            {
                                "content": "                self.render_string('with_user_module.html')",
                                "type": "added"
                            },
                            {
                                "content": "                self.finish(str(self.has_loaded_current_user))",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        return [('/without_user', WithoutUserHandler),",
                                "type": "added"
                            },
                            {
                                "content": "                ('/with_user', WithUserHandler),",
                                "type": "added"
                            },
                            {
                                "content": "                ('/without_user_module', WithoutUserModuleHandler),",
                                "type": "added"
                            },
                            {
                                "content": "                ('/with_user_module', WithUserModuleHandler)]",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    @unittest.skip('needs fix')",
                                "type": "added"
                            },
                            {
                                "content": "    def test_get_current_user_is_lazy(self):",
                                "type": "added"
                            },
                            {
                                "content": "        # TODO: Make this test pass. See #820.",
                                "type": "added"
                            },
                            {
                                "content": "        response = self.fetch('/without_user')",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(response.body, b'False')",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def test_get_current_user_works(self):",
                                "type": "added"
                            },
                            {
                                "content": "        response = self.fetch('/with_user')",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(response.body, b'True')",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def test_get_current_user_from_ui_module_is_lazy(self):",
                                "type": "added"
                            },
                            {
                                "content": "        response = self.fetch('/without_user_module')",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(response.body, b'False')",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def test_get_current_user_from_ui_module_works(self):",
                                "type": "added"
                            },
                            {
                                "content": "        response = self.fetch('/with_user_module')",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(response.body, b'True')",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "@wsgi_safe",
                                "type": "context"
                            },
                            {
                                "content": "class UnimplementedHTTPMethodsTest(SimpleHandlerTestCase):",
                                "type": "context"
                            },
                            {
                                "content": "    class Handler(RequestHandler):",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "tornado/test/web_test.py",
                            "type": "method",
                            "name": "GetCurrentUserTest.test_get_current_user_from_ui_module_works",
                            "content": "class GetCurrentUserTest(WebTestCase):\n    def get_app_kwargs(self):\n        class WithoutUserModule(UIModule):\n            def render(self):\n                return ''\n\n        class WithUserModule(UIModule):\n            def render(self):\n                return str(self.current_user)\n\n        loader = DictLoader({\n            'without_user.html': '',\n            'with_user.html': '{{ current_user }}',\n            'without_user_module.html': '{% module WithoutUserModule() %}',\n            'with_user_module.html': '{% module WithUserModule() %}',\n        })\n        return dict(template_loader=loader,\n                    ui_modules={'WithUserModule': WithUserModule,\n                                'WithoutUserModule': WithoutUserModule})\n\n    def tearDown(self):\n        super(GetCurrentUserTest, self).tearDown()\n        RequestHandler._template_loaders.clear()\n\n    def get_handlers(self):\n        class CurrentUserHandler(RequestHandler):\n            def prepare(self):\n                self.has_loaded_current_user = False\n\n            def get_current_user(self):\n                self.has_loaded_current_user = True\n                return ''\n\n        class WithoutUserHandler(CurrentUserHandler):\n            def get(self):\n                self.render_string('without_user.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class WithUserHandler(CurrentUserHandler):\n            def get(self):\n                self.render_string('with_user.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class CurrentUserModuleHandler(CurrentUserHandler):\n            def get_template_namespace(self):\n                # If RequestHandler.get_template_namespace is called, then\n                # get_current_user is evaluated. Until #820 is fixed, this\n                # is a small hack to circumvent the issue.\n                return self.ui\n\n        class WithoutUserModuleHandler(CurrentUserModuleHandler):\n            def get(self):\n                self.render_string('without_user_module.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class WithUserModuleHandler(CurrentUserModuleHandler):\n            def get(self):\n                self.render_string('with_user_module.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        return [('/without_user', WithoutUserHandler),\n                ('/with_user', WithUserHandler),\n                ('/without_user_module', WithoutUserModuleHandler),\n                ('/with_user_module', WithUserModuleHandler)]\n\n    @unittest.skip('needs fix')\n    def test_get_current_user_is_lazy(self):\n        # TODO: Make this test pass. See #820.\n        response = self.fetch('/without_user')\n        self.assertEqual(response.body, b'False')\n\n    def test_get_current_user_works(self):\n        response = self.fetch('/with_user')\n        self.assertEqual(response.body, b'True')\n\n    def test_get_current_user_from_ui_module_is_lazy(self):\n        response = self.fetch('/without_user_module')\n        self.assertEqual(response.body, b'False')\n\n    def test_get_current_user_from_ui_module_works(self):\n        response = self.fetch('/with_user_module')\n        self.assertEqual(response.body, b'True')",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 1562,
                            "end_lineno": 1564,
                            "parent": {
                                "file_name": "tornado/test/web_test.py",
                                "type": "class",
                                "name": "GetCurrentUserTest",
                                "content": "class GetCurrentUserTest(WebTestCase):\n    def get_app_kwargs(self):\n        class WithoutUserModule(UIModule):\n            def render(self):\n                return ''\n\n        class WithUserModule(UIModule):\n            def render(self):\n                return str(self.current_user)\n\n        loader = DictLoader({\n            'without_user.html': '',\n            'with_user.html': '{{ current_user }}',\n            'without_user_module.html': '{% module WithoutUserModule() %}',\n            'with_user_module.html': '{% module WithUserModule() %}',\n        })\n        return dict(template_loader=loader,\n                    ui_modules={'WithUserModule': WithUserModule,\n                                'WithoutUserModule': WithoutUserModule})\n\n    def tearDown(self):\n        super(GetCurrentUserTest, self).tearDown()\n        RequestHandler._template_loaders.clear()\n\n    def get_handlers(self):\n        class CurrentUserHandler(RequestHandler):\n            def prepare(self):\n                self.has_loaded_current_user = False\n\n            def get_current_user(self):\n                self.has_loaded_current_user = True\n                return ''\n\n        class WithoutUserHandler(CurrentUserHandler):\n            def get(self):\n                self.render_string('without_user.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class WithUserHandler(CurrentUserHandler):\n            def get(self):\n                self.render_string('with_user.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class CurrentUserModuleHandler(CurrentUserHandler):\n            def get_template_namespace(self):\n                # If RequestHandler.get_template_namespace is called, then\n                # get_current_user is evaluated. Until #820 is fixed, this\n                # is a small hack to circumvent the issue.\n                return self.ui\n\n        class WithoutUserModuleHandler(CurrentUserModuleHandler):\n            def get(self):\n                self.render_string('without_user_module.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class WithUserModuleHandler(CurrentUserModuleHandler):\n            def get(self):\n                self.render_string('with_user_module.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        return [('/without_user', WithoutUserHandler),\n                ('/with_user', WithUserHandler),\n                ('/without_user_module', WithoutUserModuleHandler),\n                ('/with_user_module', WithUserModuleHandler)]\n\n    @unittest.skip('needs fix')\n    def test_get_current_user_is_lazy(self):\n        # TODO: Make this test pass. See #820.\n        response = self.fetch('/without_user')\n        self.assertEqual(response.body, b'False')\n\n    def test_get_current_user_works(self):\n        response = self.fetch('/with_user')\n        self.assertEqual(response.body, b'True')\n\n    def test_get_current_user_from_ui_module_is_lazy(self):\n        response = self.fetch('/without_user_module')\n        self.assertEqual(response.body, b'False')\n\n    def test_get_current_user_from_ui_module_works(self):\n        response = self.fetch('/with_user_module')\n        self.assertEqual(response.body, b'True')",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 1483,
                                "end_lineno": 1564,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/test/web_test.py",
                            "type": "method",
                            "name": "GetCurrentUserTest.test_get_current_user_is_lazy",
                            "content": "class GetCurrentUserTest(WebTestCase):\n    def get_app_kwargs(self):\n        class WithoutUserModule(UIModule):\n            def render(self):\n                return ''\n\n        class WithUserModule(UIModule):\n            def render(self):\n                return str(self.current_user)\n\n        loader = DictLoader({\n            'without_user.html': '',\n            'with_user.html': '{{ current_user }}',\n            'without_user_module.html': '{% module WithoutUserModule() %}',\n            'with_user_module.html': '{% module WithUserModule() %}',\n        })\n        return dict(template_loader=loader,\n                    ui_modules={'WithUserModule': WithUserModule,\n                                'WithoutUserModule': WithoutUserModule})\n\n    def tearDown(self):\n        super(GetCurrentUserTest, self).tearDown()\n        RequestHandler._template_loaders.clear()\n\n    def get_handlers(self):\n        class CurrentUserHandler(RequestHandler):\n            def prepare(self):\n                self.has_loaded_current_user = False\n\n            def get_current_user(self):\n                self.has_loaded_current_user = True\n                return ''\n\n        class WithoutUserHandler(CurrentUserHandler):\n            def get(self):\n                self.render_string('without_user.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class WithUserHandler(CurrentUserHandler):\n            def get(self):\n                self.render_string('with_user.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class CurrentUserModuleHandler(CurrentUserHandler):\n            def get_template_namespace(self):\n                # If RequestHandler.get_template_namespace is called, then\n                # get_current_user is evaluated. Until #820 is fixed, this\n                # is a small hack to circumvent the issue.\n                return self.ui\n\n        class WithoutUserModuleHandler(CurrentUserModuleHandler):\n            def get(self):\n                self.render_string('without_user_module.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class WithUserModuleHandler(CurrentUserModuleHandler):\n            def get(self):\n                self.render_string('with_user_module.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        return [('/without_user', WithoutUserHandler),\n                ('/with_user', WithUserHandler),\n                ('/without_user_module', WithoutUserModuleHandler),\n                ('/with_user_module', WithUserModuleHandler)]\n\n    @unittest.skip('needs fix')\n    def test_get_current_user_is_lazy(self):\n        # TODO: Make this test pass. See #820.\n        response = self.fetch('/without_user')\n        self.assertEqual(response.body, b'False')\n\n    def test_get_current_user_works(self):\n        response = self.fetch('/with_user')\n        self.assertEqual(response.body, b'True')\n\n    def test_get_current_user_from_ui_module_is_lazy(self):\n        response = self.fetch('/without_user_module')\n        self.assertEqual(response.body, b'False')\n\n    def test_get_current_user_from_ui_module_works(self):\n        response = self.fetch('/with_user_module')\n        self.assertEqual(response.body, b'True')",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 1549,
                            "end_lineno": 1552,
                            "parent": {
                                "file_name": "tornado/test/web_test.py",
                                "type": "class",
                                "name": "GetCurrentUserTest",
                                "content": "class GetCurrentUserTest(WebTestCase):\n    def get_app_kwargs(self):\n        class WithoutUserModule(UIModule):\n            def render(self):\n                return ''\n\n        class WithUserModule(UIModule):\n            def render(self):\n                return str(self.current_user)\n\n        loader = DictLoader({\n            'without_user.html': '',\n            'with_user.html': '{{ current_user }}',\n            'without_user_module.html': '{% module WithoutUserModule() %}',\n            'with_user_module.html': '{% module WithUserModule() %}',\n        })\n        return dict(template_loader=loader,\n                    ui_modules={'WithUserModule': WithUserModule,\n                                'WithoutUserModule': WithoutUserModule})\n\n    def tearDown(self):\n        super(GetCurrentUserTest, self).tearDown()\n        RequestHandler._template_loaders.clear()\n\n    def get_handlers(self):\n        class CurrentUserHandler(RequestHandler):\n            def prepare(self):\n                self.has_loaded_current_user = False\n\n            def get_current_user(self):\n                self.has_loaded_current_user = True\n                return ''\n\n        class WithoutUserHandler(CurrentUserHandler):\n            def get(self):\n                self.render_string('without_user.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class WithUserHandler(CurrentUserHandler):\n            def get(self):\n                self.render_string('with_user.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class CurrentUserModuleHandler(CurrentUserHandler):\n            def get_template_namespace(self):\n                # If RequestHandler.get_template_namespace is called, then\n                # get_current_user is evaluated. Until #820 is fixed, this\n                # is a small hack to circumvent the issue.\n                return self.ui\n\n        class WithoutUserModuleHandler(CurrentUserModuleHandler):\n            def get(self):\n                self.render_string('without_user_module.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class WithUserModuleHandler(CurrentUserModuleHandler):\n            def get(self):\n                self.render_string('with_user_module.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        return [('/without_user', WithoutUserHandler),\n                ('/with_user', WithUserHandler),\n                ('/without_user_module', WithoutUserModuleHandler),\n                ('/with_user_module', WithUserModuleHandler)]\n\n    @unittest.skip('needs fix')\n    def test_get_current_user_is_lazy(self):\n        # TODO: Make this test pass. See #820.\n        response = self.fetch('/without_user')\n        self.assertEqual(response.body, b'False')\n\n    def test_get_current_user_works(self):\n        response = self.fetch('/with_user')\n        self.assertEqual(response.body, b'True')\n\n    def test_get_current_user_from_ui_module_is_lazy(self):\n        response = self.fetch('/without_user_module')\n        self.assertEqual(response.body, b'False')\n\n    def test_get_current_user_from_ui_module_works(self):\n        response = self.fetch('/with_user_module')\n        self.assertEqual(response.body, b'True')",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 1483,
                                "end_lineno": 1564,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/test/web_test.py",
                            "type": "method",
                            "name": "GetCurrentUserTest.test_get_current_user_from_ui_module_is_lazy",
                            "content": "class GetCurrentUserTest(WebTestCase):\n    def get_app_kwargs(self):\n        class WithoutUserModule(UIModule):\n            def render(self):\n                return ''\n\n        class WithUserModule(UIModule):\n            def render(self):\n                return str(self.current_user)\n\n        loader = DictLoader({\n            'without_user.html': '',\n            'with_user.html': '{{ current_user }}',\n            'without_user_module.html': '{% module WithoutUserModule() %}',\n            'with_user_module.html': '{% module WithUserModule() %}',\n        })\n        return dict(template_loader=loader,\n                    ui_modules={'WithUserModule': WithUserModule,\n                                'WithoutUserModule': WithoutUserModule})\n\n    def tearDown(self):\n        super(GetCurrentUserTest, self).tearDown()\n        RequestHandler._template_loaders.clear()\n\n    def get_handlers(self):\n        class CurrentUserHandler(RequestHandler):\n            def prepare(self):\n                self.has_loaded_current_user = False\n\n            def get_current_user(self):\n                self.has_loaded_current_user = True\n                return ''\n\n        class WithoutUserHandler(CurrentUserHandler):\n            def get(self):\n                self.render_string('without_user.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class WithUserHandler(CurrentUserHandler):\n            def get(self):\n                self.render_string('with_user.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class CurrentUserModuleHandler(CurrentUserHandler):\n            def get_template_namespace(self):\n                # If RequestHandler.get_template_namespace is called, then\n                # get_current_user is evaluated. Until #820 is fixed, this\n                # is a small hack to circumvent the issue.\n                return self.ui\n\n        class WithoutUserModuleHandler(CurrentUserModuleHandler):\n            def get(self):\n                self.render_string('without_user_module.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class WithUserModuleHandler(CurrentUserModuleHandler):\n            def get(self):\n                self.render_string('with_user_module.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        return [('/without_user', WithoutUserHandler),\n                ('/with_user', WithUserHandler),\n                ('/without_user_module', WithoutUserModuleHandler),\n                ('/with_user_module', WithUserModuleHandler)]\n\n    @unittest.skip('needs fix')\n    def test_get_current_user_is_lazy(self):\n        # TODO: Make this test pass. See #820.\n        response = self.fetch('/without_user')\n        self.assertEqual(response.body, b'False')\n\n    def test_get_current_user_works(self):\n        response = self.fetch('/with_user')\n        self.assertEqual(response.body, b'True')\n\n    def test_get_current_user_from_ui_module_is_lazy(self):\n        response = self.fetch('/without_user_module')\n        self.assertEqual(response.body, b'False')\n\n    def test_get_current_user_from_ui_module_works(self):\n        response = self.fetch('/with_user_module')\n        self.assertEqual(response.body, b'True')",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 1558,
                            "end_lineno": 1560,
                            "parent": {
                                "file_name": "tornado/test/web_test.py",
                                "type": "class",
                                "name": "GetCurrentUserTest",
                                "content": "class GetCurrentUserTest(WebTestCase):\n    def get_app_kwargs(self):\n        class WithoutUserModule(UIModule):\n            def render(self):\n                return ''\n\n        class WithUserModule(UIModule):\n            def render(self):\n                return str(self.current_user)\n\n        loader = DictLoader({\n            'without_user.html': '',\n            'with_user.html': '{{ current_user }}',\n            'without_user_module.html': '{% module WithoutUserModule() %}',\n            'with_user_module.html': '{% module WithUserModule() %}',\n        })\n        return dict(template_loader=loader,\n                    ui_modules={'WithUserModule': WithUserModule,\n                                'WithoutUserModule': WithoutUserModule})\n\n    def tearDown(self):\n        super(GetCurrentUserTest, self).tearDown()\n        RequestHandler._template_loaders.clear()\n\n    def get_handlers(self):\n        class CurrentUserHandler(RequestHandler):\n            def prepare(self):\n                self.has_loaded_current_user = False\n\n            def get_current_user(self):\n                self.has_loaded_current_user = True\n                return ''\n\n        class WithoutUserHandler(CurrentUserHandler):\n            def get(self):\n                self.render_string('without_user.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class WithUserHandler(CurrentUserHandler):\n            def get(self):\n                self.render_string('with_user.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class CurrentUserModuleHandler(CurrentUserHandler):\n            def get_template_namespace(self):\n                # If RequestHandler.get_template_namespace is called, then\n                # get_current_user is evaluated. Until #820 is fixed, this\n                # is a small hack to circumvent the issue.\n                return self.ui\n\n        class WithoutUserModuleHandler(CurrentUserModuleHandler):\n            def get(self):\n                self.render_string('without_user_module.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class WithUserModuleHandler(CurrentUserModuleHandler):\n            def get(self):\n                self.render_string('with_user_module.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        return [('/without_user', WithoutUserHandler),\n                ('/with_user', WithUserHandler),\n                ('/without_user_module', WithoutUserModuleHandler),\n                ('/with_user_module', WithUserModuleHandler)]\n\n    @unittest.skip('needs fix')\n    def test_get_current_user_is_lazy(self):\n        # TODO: Make this test pass. See #820.\n        response = self.fetch('/without_user')\n        self.assertEqual(response.body, b'False')\n\n    def test_get_current_user_works(self):\n        response = self.fetch('/with_user')\n        self.assertEqual(response.body, b'True')\n\n    def test_get_current_user_from_ui_module_is_lazy(self):\n        response = self.fetch('/without_user_module')\n        self.assertEqual(response.body, b'False')\n\n    def test_get_current_user_from_ui_module_works(self):\n        response = self.fetch('/with_user_module')\n        self.assertEqual(response.body, b'True')",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 1483,
                                "end_lineno": 1564,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/test/web_test.py",
                            "type": "method",
                            "name": "GetCurrentUserTest.tearDown",
                            "content": "class GetCurrentUserTest(WebTestCase):\n    def get_app_kwargs(self):\n        class WithoutUserModule(UIModule):\n            def render(self):\n                return ''\n\n        class WithUserModule(UIModule):\n            def render(self):\n                return str(self.current_user)\n\n        loader = DictLoader({\n            'without_user.html': '',\n            'with_user.html': '{{ current_user }}',\n            'without_user_module.html': '{% module WithoutUserModule() %}',\n            'with_user_module.html': '{% module WithUserModule() %}',\n        })\n        return dict(template_loader=loader,\n                    ui_modules={'WithUserModule': WithUserModule,\n                                'WithoutUserModule': WithoutUserModule})\n\n    def tearDown(self):\n        super(GetCurrentUserTest, self).tearDown()\n        RequestHandler._template_loaders.clear()\n\n    def get_handlers(self):\n        class CurrentUserHandler(RequestHandler):\n            def prepare(self):\n                self.has_loaded_current_user = False\n\n            def get_current_user(self):\n                self.has_loaded_current_user = True\n                return ''\n\n        class WithoutUserHandler(CurrentUserHandler):\n            def get(self):\n                self.render_string('without_user.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class WithUserHandler(CurrentUserHandler):\n            def get(self):\n                self.render_string('with_user.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class CurrentUserModuleHandler(CurrentUserHandler):\n            def get_template_namespace(self):\n                # If RequestHandler.get_template_namespace is called, then\n                # get_current_user is evaluated. Until #820 is fixed, this\n                # is a small hack to circumvent the issue.\n                return self.ui\n\n        class WithoutUserModuleHandler(CurrentUserModuleHandler):\n            def get(self):\n                self.render_string('without_user_module.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class WithUserModuleHandler(CurrentUserModuleHandler):\n            def get(self):\n                self.render_string('with_user_module.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        return [('/without_user', WithoutUserHandler),\n                ('/with_user', WithUserHandler),\n                ('/without_user_module', WithoutUserModuleHandler),\n                ('/with_user_module', WithUserModuleHandler)]\n\n    @unittest.skip('needs fix')\n    def test_get_current_user_is_lazy(self):\n        # TODO: Make this test pass. See #820.\n        response = self.fetch('/without_user')\n        self.assertEqual(response.body, b'False')\n\n    def test_get_current_user_works(self):\n        response = self.fetch('/with_user')\n        self.assertEqual(response.body, b'True')\n\n    def test_get_current_user_from_ui_module_is_lazy(self):\n        response = self.fetch('/without_user_module')\n        self.assertEqual(response.body, b'False')\n\n    def test_get_current_user_from_ui_module_works(self):\n        response = self.fetch('/with_user_module')\n        self.assertEqual(response.body, b'True')",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 1503,
                            "end_lineno": 1505,
                            "parent": {
                                "file_name": "tornado/test/web_test.py",
                                "type": "class",
                                "name": "GetCurrentUserTest",
                                "content": "class GetCurrentUserTest(WebTestCase):\n    def get_app_kwargs(self):\n        class WithoutUserModule(UIModule):\n            def render(self):\n                return ''\n\n        class WithUserModule(UIModule):\n            def render(self):\n                return str(self.current_user)\n\n        loader = DictLoader({\n            'without_user.html': '',\n            'with_user.html': '{{ current_user }}',\n            'without_user_module.html': '{% module WithoutUserModule() %}',\n            'with_user_module.html': '{% module WithUserModule() %}',\n        })\n        return dict(template_loader=loader,\n                    ui_modules={'WithUserModule': WithUserModule,\n                                'WithoutUserModule': WithoutUserModule})\n\n    def tearDown(self):\n        super(GetCurrentUserTest, self).tearDown()\n        RequestHandler._template_loaders.clear()\n\n    def get_handlers(self):\n        class CurrentUserHandler(RequestHandler):\n            def prepare(self):\n                self.has_loaded_current_user = False\n\n            def get_current_user(self):\n                self.has_loaded_current_user = True\n                return ''\n\n        class WithoutUserHandler(CurrentUserHandler):\n            def get(self):\n                self.render_string('without_user.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class WithUserHandler(CurrentUserHandler):\n            def get(self):\n                self.render_string('with_user.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class CurrentUserModuleHandler(CurrentUserHandler):\n            def get_template_namespace(self):\n                # If RequestHandler.get_template_namespace is called, then\n                # get_current_user is evaluated. Until #820 is fixed, this\n                # is a small hack to circumvent the issue.\n                return self.ui\n\n        class WithoutUserModuleHandler(CurrentUserModuleHandler):\n            def get(self):\n                self.render_string('without_user_module.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class WithUserModuleHandler(CurrentUserModuleHandler):\n            def get(self):\n                self.render_string('with_user_module.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        return [('/without_user', WithoutUserHandler),\n                ('/with_user', WithUserHandler),\n                ('/without_user_module', WithoutUserModuleHandler),\n                ('/with_user_module', WithUserModuleHandler)]\n\n    @unittest.skip('needs fix')\n    def test_get_current_user_is_lazy(self):\n        # TODO: Make this test pass. See #820.\n        response = self.fetch('/without_user')\n        self.assertEqual(response.body, b'False')\n\n    def test_get_current_user_works(self):\n        response = self.fetch('/with_user')\n        self.assertEqual(response.body, b'True')\n\n    def test_get_current_user_from_ui_module_is_lazy(self):\n        response = self.fetch('/without_user_module')\n        self.assertEqual(response.body, b'False')\n\n    def test_get_current_user_from_ui_module_works(self):\n        response = self.fetch('/with_user_module')\n        self.assertEqual(response.body, b'True')",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 1483,
                                "end_lineno": 1564,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/test/web_test.py",
                            "type": "method",
                            "name": "GetCurrentUserTest.get_handlers",
                            "content": "class GetCurrentUserTest(WebTestCase):\n    def get_app_kwargs(self):\n        class WithoutUserModule(UIModule):\n            def render(self):\n                return ''\n\n        class WithUserModule(UIModule):\n            def render(self):\n                return str(self.current_user)\n\n        loader = DictLoader({\n            'without_user.html': '',\n            'with_user.html': '{{ current_user }}',\n            'without_user_module.html': '{% module WithoutUserModule() %}',\n            'with_user_module.html': '{% module WithUserModule() %}',\n        })\n        return dict(template_loader=loader,\n                    ui_modules={'WithUserModule': WithUserModule,\n                                'WithoutUserModule': WithoutUserModule})\n\n    def tearDown(self):\n        super(GetCurrentUserTest, self).tearDown()\n        RequestHandler._template_loaders.clear()\n\n    def get_handlers(self):\n        class CurrentUserHandler(RequestHandler):\n            def prepare(self):\n                self.has_loaded_current_user = False\n\n            def get_current_user(self):\n                self.has_loaded_current_user = True\n                return ''\n\n        class WithoutUserHandler(CurrentUserHandler):\n            def get(self):\n                self.render_string('without_user.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class WithUserHandler(CurrentUserHandler):\n            def get(self):\n                self.render_string('with_user.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class CurrentUserModuleHandler(CurrentUserHandler):\n            def get_template_namespace(self):\n                # If RequestHandler.get_template_namespace is called, then\n                # get_current_user is evaluated. Until #820 is fixed, this\n                # is a small hack to circumvent the issue.\n                return self.ui\n\n        class WithoutUserModuleHandler(CurrentUserModuleHandler):\n            def get(self):\n                self.render_string('without_user_module.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class WithUserModuleHandler(CurrentUserModuleHandler):\n            def get(self):\n                self.render_string('with_user_module.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        return [('/without_user', WithoutUserHandler),\n                ('/with_user', WithUserHandler),\n                ('/without_user_module', WithoutUserModuleHandler),\n                ('/with_user_module', WithUserModuleHandler)]\n\n    @unittest.skip('needs fix')\n    def test_get_current_user_is_lazy(self):\n        # TODO: Make this test pass. See #820.\n        response = self.fetch('/without_user')\n        self.assertEqual(response.body, b'False')\n\n    def test_get_current_user_works(self):\n        response = self.fetch('/with_user')\n        self.assertEqual(response.body, b'True')\n\n    def test_get_current_user_from_ui_module_is_lazy(self):\n        response = self.fetch('/without_user_module')\n        self.assertEqual(response.body, b'False')\n\n    def test_get_current_user_from_ui_module_works(self):\n        response = self.fetch('/with_user_module')\n        self.assertEqual(response.body, b'True')",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 1507,
                            "end_lineno": 1546,
                            "parent": {
                                "file_name": "tornado/test/web_test.py",
                                "type": "class",
                                "name": "GetCurrentUserTest",
                                "content": "class GetCurrentUserTest(WebTestCase):\n    def get_app_kwargs(self):\n        class WithoutUserModule(UIModule):\n            def render(self):\n                return ''\n\n        class WithUserModule(UIModule):\n            def render(self):\n                return str(self.current_user)\n\n        loader = DictLoader({\n            'without_user.html': '',\n            'with_user.html': '{{ current_user }}',\n            'without_user_module.html': '{% module WithoutUserModule() %}',\n            'with_user_module.html': '{% module WithUserModule() %}',\n        })\n        return dict(template_loader=loader,\n                    ui_modules={'WithUserModule': WithUserModule,\n                                'WithoutUserModule': WithoutUserModule})\n\n    def tearDown(self):\n        super(GetCurrentUserTest, self).tearDown()\n        RequestHandler._template_loaders.clear()\n\n    def get_handlers(self):\n        class CurrentUserHandler(RequestHandler):\n            def prepare(self):\n                self.has_loaded_current_user = False\n\n            def get_current_user(self):\n                self.has_loaded_current_user = True\n                return ''\n\n        class WithoutUserHandler(CurrentUserHandler):\n            def get(self):\n                self.render_string('without_user.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class WithUserHandler(CurrentUserHandler):\n            def get(self):\n                self.render_string('with_user.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class CurrentUserModuleHandler(CurrentUserHandler):\n            def get_template_namespace(self):\n                # If RequestHandler.get_template_namespace is called, then\n                # get_current_user is evaluated. Until #820 is fixed, this\n                # is a small hack to circumvent the issue.\n                return self.ui\n\n        class WithoutUserModuleHandler(CurrentUserModuleHandler):\n            def get(self):\n                self.render_string('without_user_module.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class WithUserModuleHandler(CurrentUserModuleHandler):\n            def get(self):\n                self.render_string('with_user_module.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        return [('/without_user', WithoutUserHandler),\n                ('/with_user', WithUserHandler),\n                ('/without_user_module', WithoutUserModuleHandler),\n                ('/with_user_module', WithUserModuleHandler)]\n\n    @unittest.skip('needs fix')\n    def test_get_current_user_is_lazy(self):\n        # TODO: Make this test pass. See #820.\n        response = self.fetch('/without_user')\n        self.assertEqual(response.body, b'False')\n\n    def test_get_current_user_works(self):\n        response = self.fetch('/with_user')\n        self.assertEqual(response.body, b'True')\n\n    def test_get_current_user_from_ui_module_is_lazy(self):\n        response = self.fetch('/without_user_module')\n        self.assertEqual(response.body, b'False')\n\n    def test_get_current_user_from_ui_module_works(self):\n        response = self.fetch('/with_user_module')\n        self.assertEqual(response.body, b'True')",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 1483,
                                "end_lineno": 1564,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/test/web_test.py",
                            "type": "method",
                            "name": "GetCurrentUserTest.get_app_kwargs",
                            "content": "class GetCurrentUserTest(WebTestCase):\n    def get_app_kwargs(self):\n        class WithoutUserModule(UIModule):\n            def render(self):\n                return ''\n\n        class WithUserModule(UIModule):\n            def render(self):\n                return str(self.current_user)\n\n        loader = DictLoader({\n            'without_user.html': '',\n            'with_user.html': '{{ current_user }}',\n            'without_user_module.html': '{% module WithoutUserModule() %}',\n            'with_user_module.html': '{% module WithUserModule() %}',\n        })\n        return dict(template_loader=loader,\n                    ui_modules={'WithUserModule': WithUserModule,\n                                'WithoutUserModule': WithoutUserModule})\n\n    def tearDown(self):\n        super(GetCurrentUserTest, self).tearDown()\n        RequestHandler._template_loaders.clear()\n\n    def get_handlers(self):\n        class CurrentUserHandler(RequestHandler):\n            def prepare(self):\n                self.has_loaded_current_user = False\n\n            def get_current_user(self):\n                self.has_loaded_current_user = True\n                return ''\n\n        class WithoutUserHandler(CurrentUserHandler):\n            def get(self):\n                self.render_string('without_user.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class WithUserHandler(CurrentUserHandler):\n            def get(self):\n                self.render_string('with_user.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class CurrentUserModuleHandler(CurrentUserHandler):\n            def get_template_namespace(self):\n                # If RequestHandler.get_template_namespace is called, then\n                # get_current_user is evaluated. Until #820 is fixed, this\n                # is a small hack to circumvent the issue.\n                return self.ui\n\n        class WithoutUserModuleHandler(CurrentUserModuleHandler):\n            def get(self):\n                self.render_string('without_user_module.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class WithUserModuleHandler(CurrentUserModuleHandler):\n            def get(self):\n                self.render_string('with_user_module.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        return [('/without_user', WithoutUserHandler),\n                ('/with_user', WithUserHandler),\n                ('/without_user_module', WithoutUserModuleHandler),\n                ('/with_user_module', WithUserModuleHandler)]\n\n    @unittest.skip('needs fix')\n    def test_get_current_user_is_lazy(self):\n        # TODO: Make this test pass. See #820.\n        response = self.fetch('/without_user')\n        self.assertEqual(response.body, b'False')\n\n    def test_get_current_user_works(self):\n        response = self.fetch('/with_user')\n        self.assertEqual(response.body, b'True')\n\n    def test_get_current_user_from_ui_module_is_lazy(self):\n        response = self.fetch('/without_user_module')\n        self.assertEqual(response.body, b'False')\n\n    def test_get_current_user_from_ui_module_works(self):\n        response = self.fetch('/with_user_module')\n        self.assertEqual(response.body, b'True')",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 1484,
                            "end_lineno": 1501,
                            "parent": {
                                "file_name": "tornado/test/web_test.py",
                                "type": "class",
                                "name": "GetCurrentUserTest",
                                "content": "class GetCurrentUserTest(WebTestCase):\n    def get_app_kwargs(self):\n        class WithoutUserModule(UIModule):\n            def render(self):\n                return ''\n\n        class WithUserModule(UIModule):\n            def render(self):\n                return str(self.current_user)\n\n        loader = DictLoader({\n            'without_user.html': '',\n            'with_user.html': '{{ current_user }}',\n            'without_user_module.html': '{% module WithoutUserModule() %}',\n            'with_user_module.html': '{% module WithUserModule() %}',\n        })\n        return dict(template_loader=loader,\n                    ui_modules={'WithUserModule': WithUserModule,\n                                'WithoutUserModule': WithoutUserModule})\n\n    def tearDown(self):\n        super(GetCurrentUserTest, self).tearDown()\n        RequestHandler._template_loaders.clear()\n\n    def get_handlers(self):\n        class CurrentUserHandler(RequestHandler):\n            def prepare(self):\n                self.has_loaded_current_user = False\n\n            def get_current_user(self):\n                self.has_loaded_current_user = True\n                return ''\n\n        class WithoutUserHandler(CurrentUserHandler):\n            def get(self):\n                self.render_string('without_user.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class WithUserHandler(CurrentUserHandler):\n            def get(self):\n                self.render_string('with_user.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class CurrentUserModuleHandler(CurrentUserHandler):\n            def get_template_namespace(self):\n                # If RequestHandler.get_template_namespace is called, then\n                # get_current_user is evaluated. Until #820 is fixed, this\n                # is a small hack to circumvent the issue.\n                return self.ui\n\n        class WithoutUserModuleHandler(CurrentUserModuleHandler):\n            def get(self):\n                self.render_string('without_user_module.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class WithUserModuleHandler(CurrentUserModuleHandler):\n            def get(self):\n                self.render_string('with_user_module.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        return [('/without_user', WithoutUserHandler),\n                ('/with_user', WithUserHandler),\n                ('/without_user_module', WithoutUserModuleHandler),\n                ('/with_user_module', WithUserModuleHandler)]\n\n    @unittest.skip('needs fix')\n    def test_get_current_user_is_lazy(self):\n        # TODO: Make this test pass. See #820.\n        response = self.fetch('/without_user')\n        self.assertEqual(response.body, b'False')\n\n    def test_get_current_user_works(self):\n        response = self.fetch('/with_user')\n        self.assertEqual(response.body, b'True')\n\n    def test_get_current_user_from_ui_module_is_lazy(self):\n        response = self.fetch('/without_user_module')\n        self.assertEqual(response.body, b'False')\n\n    def test_get_current_user_from_ui_module_works(self):\n        response = self.fetch('/with_user_module')\n        self.assertEqual(response.body, b'True')",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 1483,
                                "end_lineno": 1564,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/test/web_test.py",
                            "type": "method",
                            "name": "GetCurrentUserTest.test_get_current_user_works",
                            "content": "class GetCurrentUserTest(WebTestCase):\n    def get_app_kwargs(self):\n        class WithoutUserModule(UIModule):\n            def render(self):\n                return ''\n\n        class WithUserModule(UIModule):\n            def render(self):\n                return str(self.current_user)\n\n        loader = DictLoader({\n            'without_user.html': '',\n            'with_user.html': '{{ current_user }}',\n            'without_user_module.html': '{% module WithoutUserModule() %}',\n            'with_user_module.html': '{% module WithUserModule() %}',\n        })\n        return dict(template_loader=loader,\n                    ui_modules={'WithUserModule': WithUserModule,\n                                'WithoutUserModule': WithoutUserModule})\n\n    def tearDown(self):\n        super(GetCurrentUserTest, self).tearDown()\n        RequestHandler._template_loaders.clear()\n\n    def get_handlers(self):\n        class CurrentUserHandler(RequestHandler):\n            def prepare(self):\n                self.has_loaded_current_user = False\n\n            def get_current_user(self):\n                self.has_loaded_current_user = True\n                return ''\n\n        class WithoutUserHandler(CurrentUserHandler):\n            def get(self):\n                self.render_string('without_user.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class WithUserHandler(CurrentUserHandler):\n            def get(self):\n                self.render_string('with_user.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class CurrentUserModuleHandler(CurrentUserHandler):\n            def get_template_namespace(self):\n                # If RequestHandler.get_template_namespace is called, then\n                # get_current_user is evaluated. Until #820 is fixed, this\n                # is a small hack to circumvent the issue.\n                return self.ui\n\n        class WithoutUserModuleHandler(CurrentUserModuleHandler):\n            def get(self):\n                self.render_string('without_user_module.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class WithUserModuleHandler(CurrentUserModuleHandler):\n            def get(self):\n                self.render_string('with_user_module.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        return [('/without_user', WithoutUserHandler),\n                ('/with_user', WithUserHandler),\n                ('/without_user_module', WithoutUserModuleHandler),\n                ('/with_user_module', WithUserModuleHandler)]\n\n    @unittest.skip('needs fix')\n    def test_get_current_user_is_lazy(self):\n        # TODO: Make this test pass. See #820.\n        response = self.fetch('/without_user')\n        self.assertEqual(response.body, b'False')\n\n    def test_get_current_user_works(self):\n        response = self.fetch('/with_user')\n        self.assertEqual(response.body, b'True')\n\n    def test_get_current_user_from_ui_module_is_lazy(self):\n        response = self.fetch('/without_user_module')\n        self.assertEqual(response.body, b'False')\n\n    def test_get_current_user_from_ui_module_works(self):\n        response = self.fetch('/with_user_module')\n        self.assertEqual(response.body, b'True')",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 1554,
                            "end_lineno": 1556,
                            "parent": {
                                "file_name": "tornado/test/web_test.py",
                                "type": "class",
                                "name": "GetCurrentUserTest",
                                "content": "class GetCurrentUserTest(WebTestCase):\n    def get_app_kwargs(self):\n        class WithoutUserModule(UIModule):\n            def render(self):\n                return ''\n\n        class WithUserModule(UIModule):\n            def render(self):\n                return str(self.current_user)\n\n        loader = DictLoader({\n            'without_user.html': '',\n            'with_user.html': '{{ current_user }}',\n            'without_user_module.html': '{% module WithoutUserModule() %}',\n            'with_user_module.html': '{% module WithUserModule() %}',\n        })\n        return dict(template_loader=loader,\n                    ui_modules={'WithUserModule': WithUserModule,\n                                'WithoutUserModule': WithoutUserModule})\n\n    def tearDown(self):\n        super(GetCurrentUserTest, self).tearDown()\n        RequestHandler._template_loaders.clear()\n\n    def get_handlers(self):\n        class CurrentUserHandler(RequestHandler):\n            def prepare(self):\n                self.has_loaded_current_user = False\n\n            def get_current_user(self):\n                self.has_loaded_current_user = True\n                return ''\n\n        class WithoutUserHandler(CurrentUserHandler):\n            def get(self):\n                self.render_string('without_user.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class WithUserHandler(CurrentUserHandler):\n            def get(self):\n                self.render_string('with_user.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class CurrentUserModuleHandler(CurrentUserHandler):\n            def get_template_namespace(self):\n                # If RequestHandler.get_template_namespace is called, then\n                # get_current_user is evaluated. Until #820 is fixed, this\n                # is a small hack to circumvent the issue.\n                return self.ui\n\n        class WithoutUserModuleHandler(CurrentUserModuleHandler):\n            def get(self):\n                self.render_string('without_user_module.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class WithUserModuleHandler(CurrentUserModuleHandler):\n            def get(self):\n                self.render_string('with_user_module.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        return [('/without_user', WithoutUserHandler),\n                ('/with_user', WithUserHandler),\n                ('/without_user_module', WithoutUserModuleHandler),\n                ('/with_user_module', WithUserModuleHandler)]\n\n    @unittest.skip('needs fix')\n    def test_get_current_user_is_lazy(self):\n        # TODO: Make this test pass. See #820.\n        response = self.fetch('/without_user')\n        self.assertEqual(response.body, b'False')\n\n    def test_get_current_user_works(self):\n        response = self.fetch('/with_user')\n        self.assertEqual(response.body, b'True')\n\n    def test_get_current_user_from_ui_module_is_lazy(self):\n        response = self.fetch('/without_user_module')\n        self.assertEqual(response.body, b'False')\n\n    def test_get_current_user_from_ui_module_works(self):\n        response = self.fetch('/with_user_module')\n        self.assertEqual(response.body, b'True')",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 1483,
                                "end_lineno": 1564,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/test/web_test.py",
                            "type": "class",
                            "name": "GetCurrentUserTest",
                            "content": "class GetCurrentUserTest(WebTestCase):\n    def get_app_kwargs(self):\n        class WithoutUserModule(UIModule):\n            def render(self):\n                return ''\n\n        class WithUserModule(UIModule):\n            def render(self):\n                return str(self.current_user)\n\n        loader = DictLoader({\n            'without_user.html': '',\n            'with_user.html': '{{ current_user }}',\n            'without_user_module.html': '{% module WithoutUserModule() %}',\n            'with_user_module.html': '{% module WithUserModule() %}',\n        })\n        return dict(template_loader=loader,\n                    ui_modules={'WithUserModule': WithUserModule,\n                                'WithoutUserModule': WithoutUserModule})\n\n    def tearDown(self):\n        super(GetCurrentUserTest, self).tearDown()\n        RequestHandler._template_loaders.clear()\n\n    def get_handlers(self):\n        class CurrentUserHandler(RequestHandler):\n            def prepare(self):\n                self.has_loaded_current_user = False\n\n            def get_current_user(self):\n                self.has_loaded_current_user = True\n                return ''\n\n        class WithoutUserHandler(CurrentUserHandler):\n            def get(self):\n                self.render_string('without_user.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class WithUserHandler(CurrentUserHandler):\n            def get(self):\n                self.render_string('with_user.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class CurrentUserModuleHandler(CurrentUserHandler):\n            def get_template_namespace(self):\n                # If RequestHandler.get_template_namespace is called, then\n                # get_current_user is evaluated. Until #820 is fixed, this\n                # is a small hack to circumvent the issue.\n                return self.ui\n\n        class WithoutUserModuleHandler(CurrentUserModuleHandler):\n            def get(self):\n                self.render_string('without_user_module.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class WithUserModuleHandler(CurrentUserModuleHandler):\n            def get(self):\n                self.render_string('with_user_module.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        return [('/without_user', WithoutUserHandler),\n                ('/with_user', WithUserHandler),\n                ('/without_user_module', WithoutUserModuleHandler),\n                ('/with_user_module', WithUserModuleHandler)]\n\n    @unittest.skip('needs fix')\n    def test_get_current_user_is_lazy(self):\n        # TODO: Make this test pass. See #820.\n        response = self.fetch('/without_user')\n        self.assertEqual(response.body, b'False')\n\n    def test_get_current_user_works(self):\n        response = self.fetch('/with_user')\n        self.assertEqual(response.body, b'True')\n\n    def test_get_current_user_from_ui_module_is_lazy(self):\n        response = self.fetch('/without_user_module')\n        self.assertEqual(response.body, b'False')\n\n    def test_get_current_user_from_ui_module_works(self):\n        response = self.fetch('/with_user_module')\n        self.assertEqual(response.body, b'True')",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 1483,
                            "end_lineno": 1564,
                            "parent": null
                        }
                    ],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "#!/usr/bin/env python\n#\n# Copyright 2009 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"``tornado.web`` provides a simple web framework with asynchronous\nfeatures that allow it to scale to large numbers of open connections,\nmaking it ideal for `long polling\n<http://en.wikipedia.org/wiki/Push_technology#Long_polling>`_.\n\nHere is a simple \"Hello, world\" example app::\n\n    import tornado.ioloop\n    import tornado.web\n\n    class MainHandler(tornado.web.RequestHandler):\n        def get(self):\n            self.write(\"Hello, world\")\n\n    if __name__ == \"__main__\":\n        application = tornado.web.Application([\n            (r\"/\", MainHandler),\n        ])\n        application.listen(8888)\n        tornado.ioloop.IOLoop.instance().start()\n\nSee the :doc:`Tornado overview <overview>` for more details and a good getting\nstarted guide.\n\nThread-safety notes\n-------------------\n\nIn general, methods on `RequestHandler` and elsewhere in Tornado are\nnot thread-safe.  In particular, methods such as\n`~RequestHandler.write()`, `~RequestHandler.finish()`, and\n`~RequestHandler.flush()` must only be called from the main thread.  If\nyou use multiple threads it is important to use `.IOLoop.add_callback`\nto transfer control back to the main thread before finishing the\nrequest.\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function, with_statement\n\n\nimport base64\nimport binascii\nimport datetime\nimport email.utils\nimport functools\nimport gzip\nimport hashlib\nimport hmac\nimport mimetypes\nimport numbers\nimport os.path\nimport re\nimport stat\nimport sys\nimport threading\nimport time\nimport tornado\nimport traceback\nimport types\nimport uuid\n\nfrom tornado.concurrent import Future\nfrom tornado import escape\nfrom tornado import httputil\nfrom tornado import locale\nfrom tornado.log import access_log, app_log, gen_log\nfrom tornado import stack_context\nfrom tornado import template\nfrom tornado.escape import utf8, _unicode\nfrom tornado.util import bytes_type, import_object, ObjectDict, raise_exc_info, unicode_type\n\ntry:\n    from io import BytesIO  # python 3\nexcept ImportError:\n    from cStringIO import StringIO as BytesIO  # python 2\n\ntry:\n    import Cookie  # py2\nexcept ImportError:\n    import http.cookies as Cookie  # py3\n\ntry:\n    import urlparse  # py2\nexcept ImportError:\n    import urllib.parse as urlparse  # py3\n\ntry:\n    from urllib import urlencode  # py2\nexcept ImportError:\n    from urllib.parse import urlencode  # py3\n\n\nclass RequestHandler(object):\n    \"\"\"Subclass this class and define `get()` or `post()` to make a handler.\n\n    If you want to support more methods than the standard GET/HEAD/POST, you\n    should override the class variable ``SUPPORTED_METHODS`` in your\n    `RequestHandler` subclass.\n    \"\"\"\n    SUPPORTED_METHODS = (\"GET\", \"HEAD\", \"POST\", \"DELETE\", \"PATCH\", \"PUT\",\n                         \"OPTIONS\")\n\n    _template_loaders = {}  # {path: template.BaseLoader}\n    _template_loader_lock = threading.Lock()\n    _remove_control_chars_regex = re.compile(r\"[\\x00-\\x08\\x0e-\\x1f]\")\n\n    def __init__(self, application, request, **kwargs):\n        super(RequestHandler, self).__init__()\n\n        self.application = application\n        self.request = request\n        self._headers_written = False\n        self._finished = False\n        self._auto_finish = True\n        self._transforms = None  # will be set in _execute\n        self.path_args = None\n        self.path_kwargs = None\n        self.ui = ObjectDict((n, self._ui_method(m)) for n, m in\n                             application.ui_methods.items())\n        # UIModules are available as both `modules` and `_tt_modules` in the\n        # template namespace.  Historically only `modules` was available\n        # but could be clobbered by user additions to the namespace.\n        # The template {% module %} directive looks in `_tt_modules` to avoid\n        # possible conflicts.\n        self.ui[\"_tt_modules\"] = _UIModuleNamespace(self,\n                                                    application.ui_modules)\n        self.ui[\"modules\"] = self.ui[\"_tt_modules\"]\n        self.clear()\n        # Check since connection is not available in WSGI\n        if getattr(self.request, \"connection\", None):\n            self.request.connection.set_close_callback(\n                self.on_connection_close)\n        self.initialize(**kwargs)\n\n    def initialize(self):\n        \"\"\"Hook for subclass initialization.\n\n        A dictionary passed as the third argument of a url spec will be\n        supplied as keyword arguments to initialize().\n\n        Example::\n\n            class ProfileHandler(RequestHandler):\n                def initialize(self, database):\n                    self.database = database\n\n                def get(self, username):\n                    ...\n\n            app = Application([\n                (r'/user/(.*)', ProfileHandler, dict(database=database)),\n                ])\n        \"\"\"\n        pass\n\n    @property\n    def settings(self):\n        \"\"\"An alias for `self.application.settings <Application.settings>`.\"\"\"\n        return self.application.settings\n\n    def head(self, *args, **kwargs):\n        raise HTTPError(405)\n\n    def get(self, *args, **kwargs):\n        raise HTTPError(405)\n\n    def post(self, *args, **kwargs):\n        raise HTTPError(405)\n\n    def delete(self, *args, **kwargs):\n        raise HTTPError(405)\n\n    def patch(self, *args, **kwargs):\n        raise HTTPError(405)\n\n    def put(self, *args, **kwargs):\n        raise HTTPError(405)\n\n    def options(self, *args, **kwargs):\n        raise HTTPError(405)\n\n    def prepare(self):\n        \"\"\"Called at the beginning of a request before  `get`/`post`/etc.\n\n        Override this method to perform common initialization regardless\n        of the request method.\n\n        Asynchronous support: Decorate this method with `.gen.coroutine`\n        or `.return_future` to make it asynchronous (the\n        `asynchronous` decorator cannot be used on `prepare`).\n        If this method returns a `.Future` execution will not proceed\n        until the `.Future` is done.\n\n        .. versionadded:: 3.1\n           Asynchronous support.\n        \"\"\"\n        pass\n\n    def on_finish(self):\n        \"\"\"Called after the end of a request.\n\n        Override this method to perform cleanup, logging, etc.\n        This method is a counterpart to `prepare`.  ``on_finish`` may\n        not produce any output, as it is called after the response\n        has been sent to the client.\n        \"\"\"\n        pass\n\n    def on_connection_close(self):\n        \"\"\"Called in async handlers if the client closed the connection.\n\n        Override this to clean up resources associated with\n        long-lived connections.  Note that this method is called only if\n        the connection was closed during asynchronous processing; if you\n        need to do cleanup after every request override `on_finish`\n        instead.\n\n        Proxies may keep a connection open for a time (perhaps\n        indefinitely) after the client has gone away, so this method\n        may not be called promptly after the end user closes their\n        connection.\n        \"\"\"\n        pass\n\n    def clear(self):\n        \"\"\"Resets all headers and content for this response.\"\"\"\n        self._headers = httputil.HTTPHeaders({\n            \"Server\": \"TornadoServer/%s\" % tornado.version,\n            \"Content-Type\": \"text/html; charset=UTF-8\",\n            \"Date\": httputil.format_timestamp(time.time()),\n        })\n        self.set_default_headers()\n        if (not self.request.supports_http_1_1() and\n            getattr(self.request, 'connection', None) and\n                not self.request.connection.no_keep_alive):\n            conn_header = self.request.headers.get(\"Connection\")\n            if conn_header and (conn_header.lower() == \"keep-alive\"):\n                self.set_header(\"Connection\", \"Keep-Alive\")\n        self._write_buffer = []\n        self._status_code = 200\n        self._reason = httputil.responses[200]\n\n    def set_default_headers(self):\n        \"\"\"Override this to set HTTP headers at the beginning of the request.\n\n        For example, this is the place to set a custom ``Server`` header.\n        Note that setting such headers in the normal flow of request\n        processing may not do what you want, since headers may be reset\n        during error handling.\n        \"\"\"\n        pass\n\n    def set_status(self, status_code, reason=None):\n        \"\"\"Sets the status code for our response.\n\n        :arg int status_code: Response status code. If ``reason`` is ``None``,\n            it must be present in `httplib.responses <http.client.responses>`.\n        :arg string reason: Human-readable reason phrase describing the status\n            code. If ``None``, it will be filled in from\n            `httplib.responses <http.client.responses>`.\n        \"\"\"\n        self._status_code = status_code\n        if reason is not None:\n            self._reason = escape.native_str(reason)\n        else:\n            try:\n                self._reason = httputil.responses[status_code]\n            except KeyError:\n                raise ValueError(\"unknown status code %d\", status_code)\n\n    def get_status(self):\n        \"\"\"Returns the status code for our response.\"\"\"\n        return self._status_code\n\n    def set_header(self, name, value):\n        \"\"\"Sets the given response header name and value.\n\n        If a datetime is given, we automatically format it according to the\n        HTTP specification. If the value is not a string, we convert it to\n        a string. All header values are then encoded as UTF-8.\n        \"\"\"\n        self._headers[name] = self._convert_header_value(value)\n\n    def add_header(self, name, value):\n        \"\"\"Adds the given response header and value.\n\n        Unlike `set_header`, `add_header` may be called multiple times\n        to return multiple values for the same header.\n        \"\"\"\n        self._headers.add(name, self._convert_header_value(value))\n\n    def clear_header(self, name):\n        \"\"\"Clears an outgoing header, undoing a previous `set_header` call.\n\n        Note that this method does not apply to multi-valued headers\n        set by `add_header`.\n        \"\"\"\n        if name in self._headers:\n            del self._headers[name]\n\n    _INVALID_HEADER_CHAR_RE = re.compile(br\"[\\x00-\\x1f]\")\n\n    def _convert_header_value(self, value):\n        if isinstance(value, bytes_type):\n            pass\n        elif isinstance(value, unicode_type):\n            value = value.encode('utf-8')\n        elif isinstance(value, numbers.Integral):\n            # return immediately since we know the converted value will be safe\n            return str(value)\n        elif isinstance(value, datetime.datetime):\n            return httputil.format_timestamp(value)\n        else:\n            raise TypeError(\"Unsupported header value %r\" % value)\n        # If \\n is allowed into the header, it is possible to inject\n        # additional headers or split the request. Also cap length to\n        # prevent obviously erroneous values.\n        if (len(value) > 4000 or\n                RequestHandler._INVALID_HEADER_CHAR_RE.search(value)):\n            raise ValueError(\"Unsafe header value %r\", value)\n        return value\n\n    _ARG_DEFAULT = []\n\n    def get_argument(self, name, default=_ARG_DEFAULT, strip=True):\n        \"\"\"Returns the value of the argument with the given name.\n\n        If default is not provided, the argument is considered to be\n        required, and we raise a `MissingArgumentError` if it is missing.\n\n        If the argument appears in the url more than once, we return the\n        last value.\n\n        The returned value is always unicode.\n        \"\"\"\n        args = self.get_arguments(name, strip=strip)\n        if not args:\n            if default is self._ARG_DEFAULT:\n                raise MissingArgumentError(name)\n            return default\n        return args[-1]\n\n    def get_arguments(self, name, strip=True):\n        \"\"\"Returns a list of the arguments with the given name.\n\n        If the argument is not present, returns an empty list.\n\n        The returned values are always unicode.\n        \"\"\"\n\n        values = []\n        for v in self.request.arguments.get(name, []):\n            v = self.decode_argument(v, name=name)\n            if isinstance(v, unicode_type):\n                # Get rid of any weird control chars (unless decoding gave\n                # us bytes, in which case leave it alone)\n                v = RequestHandler._remove_control_chars_regex.sub(\" \", v)\n            if strip:\n                v = v.strip()\n            values.append(v)\n        return values\n\n    def decode_argument(self, value, name=None):\n        \"\"\"Decodes an argument from the request.\n\n        The argument has been percent-decoded and is now a byte string.\n        By default, this method decodes the argument as utf-8 and returns\n        a unicode string, but this may be overridden in subclasses.\n\n        This method is used as a filter for both `get_argument()` and for\n        values extracted from the url and passed to `get()`/`post()`/etc.\n\n        The name of the argument is provided if known, but may be None\n        (e.g. for unnamed groups in the url regex).\n        \"\"\"\n        return _unicode(value)\n\n    @property\n    def cookies(self):\n        \"\"\"An alias for `self.request.cookies <.httpserver.HTTPRequest.cookies>`.\"\"\"\n        return self.request.cookies\n\n    def get_cookie(self, name, default=None):\n        \"\"\"Gets the value of the cookie with the given name, else default.\"\"\"\n        if self.request.cookies is not None and name in self.request.cookies:\n            return self.request.cookies[name].value\n        return default\n\n    def set_cookie(self, name, value, domain=None, expires=None, path=\"/\",\n                   expires_days=None, **kwargs):\n        \"\"\"Sets the given cookie name/value with the given options.\n\n        Additional keyword arguments are set on the Cookie.Morsel\n        directly.\n        See http://docs.python.org/library/cookie.html#morsel-objects\n        for available attributes.\n        \"\"\"\n        # The cookie library only accepts type str, in both python 2 and 3\n        name = escape.native_str(name)\n        value = escape.native_str(value)\n        if re.search(r\"[\\x00-\\x20]\", name + value):\n            # Don't let us accidentally inject bad stuff\n            raise ValueError(\"Invalid cookie %r: %r\" % (name, value))\n        if not hasattr(self, \"_new_cookie\"):\n            self._new_cookie = Cookie.SimpleCookie()\n        if name in self._new_cookie:\n            del self._new_cookie[name]\n        self._new_cookie[name] = value\n        morsel = self._new_cookie[name]\n        if domain:\n            morsel[\"domain\"] = domain\n        if expires_days is not None and not expires:\n            expires = datetime.datetime.utcnow() + datetime.timedelta(\n                days=expires_days)\n        if expires:\n            morsel[\"expires\"] = httputil.format_timestamp(expires)\n        if path:\n            morsel[\"path\"] = path\n        for k, v in kwargs.items():\n            if k == 'max_age':\n                k = 'max-age'\n            morsel[k] = v\n\n    def clear_cookie(self, name, path=\"/\", domain=None):\n        \"\"\"Deletes the cookie with the given name.\"\"\"\n        expires = datetime.datetime.utcnow() - datetime.timedelta(days=365)\n        self.set_cookie(name, value=\"\", path=path, expires=expires,\n                        domain=domain)\n\n    def clear_all_cookies(self):\n        \"\"\"Deletes all the cookies the user sent with this request.\"\"\"\n        for name in self.request.cookies:\n            self.clear_cookie(name)\n\n    def set_secure_cookie(self, name, value, expires_days=30, **kwargs):\n        \"\"\"Signs and timestamps a cookie so it cannot be forged.\n\n        You must specify the ``cookie_secret`` setting in your Application\n        to use this method. It should be a long, random sequence of bytes\n        to be used as the HMAC secret for the signature.\n\n        To read a cookie set with this method, use `get_secure_cookie()`.\n\n        Note that the ``expires_days`` parameter sets the lifetime of the\n        cookie in the browser, but is independent of the ``max_age_days``\n        parameter to `get_secure_cookie`.\n\n        Secure cookies may contain arbitrary byte values, not just unicode\n        strings (unlike regular cookies)\n        \"\"\"\n        self.set_cookie(name, self.create_signed_value(name, value),\n                        expires_days=expires_days, **kwargs)\n\n    def create_signed_value(self, name, value):\n        \"\"\"Signs and timestamps a string so it cannot be forged.\n\n        Normally used via set_secure_cookie, but provided as a separate\n        method for non-cookie uses.  To decode a value not stored\n        as a cookie use the optional value argument to get_secure_cookie.\n        \"\"\"\n        self.require_setting(\"cookie_secret\", \"secure cookies\")\n        return create_signed_value(self.application.settings[\"cookie_secret\"],\n                                   name, value)\n\n    def get_secure_cookie(self, name, value=None, max_age_days=31):\n        \"\"\"Returns the given signed cookie if it validates, or None.\n\n        The decoded cookie value is returned as a byte string (unlike\n        `get_cookie`).\n        \"\"\"\n        self.require_setting(\"cookie_secret\", \"secure cookies\")\n        if value is None:\n            value = self.get_cookie(name)\n        return decode_signed_value(self.application.settings[\"cookie_secret\"],\n                                   name, value, max_age_days=max_age_days)\n\n    def redirect(self, url, permanent=False, status=None):\n        \"\"\"Sends a redirect to the given (optionally relative) URL.\n\n        If the ``status`` argument is specified, that value is used as the\n        HTTP status code; otherwise either 301 (permanent) or 302\n        (temporary) is chosen based on the ``permanent`` argument.\n        The default is 302 (temporary).\n        \"\"\"\n        if self._headers_written:\n            raise Exception(\"Cannot redirect after headers have been written\")\n        if status is None:\n            status = 301 if permanent else 302\n        else:\n            assert isinstance(status, int) and 300 <= status <= 399\n        self.set_status(status)\n        self.set_header(\"Location\", urlparse.urljoin(utf8(self.request.uri),\n                                                     utf8(url)))\n        self.finish()\n\n    def write(self, chunk):\n        \"\"\"Writes the given chunk to the output buffer.\n\n        To write the output to the network, use the flush() method below.\n\n        If the given chunk is a dictionary, we write it as JSON and set\n        the Content-Type of the response to be ``application/json``.\n        (if you want to send JSON as a different ``Content-Type``, call\n        set_header *after* calling write()).\n\n        Note that lists are not converted to JSON because of a potential\n        cross-site security vulnerability.  All JSON output should be\n        wrapped in a dictionary.  More details at\n        http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx\n        \"\"\"\n        if self._finished:\n            raise RuntimeError(\"Cannot write() after finish().  May be caused \"\n                               \"by using async operations without the \"\n                               \"@asynchronous decorator.\")\n        if isinstance(chunk, dict):\n            chunk = escape.json_encode(chunk)\n            self.set_header(\"Content-Type\", \"application/json; charset=UTF-8\")\n        chunk = utf8(chunk)\n        self._write_buffer.append(chunk)\n\n    def render(self, template_name, **kwargs):\n        \"\"\"Renders the template with the given arguments as the response.\"\"\"\n        html = self.render_string(template_name, **kwargs)\n\n        # Insert the additional JS and CSS added by the modules on the page\n        js_embed = []\n        js_files = []\n        css_embed = []\n        css_files = []\n        html_heads = []\n        html_bodies = []\n        for module in getattr(self, \"_active_modules\", {}).values():\n            embed_part = module.embedded_javascript()\n            if embed_part:\n                js_embed.append(utf8(embed_part))\n            file_part = module.javascript_files()\n            if file_part:\n                if isinstance(file_part, (unicode_type, bytes_type)):\n                    js_files.append(file_part)\n                else:\n                    js_files.extend(file_part)\n            embed_part = module.embedded_css()\n            if embed_part:\n                css_embed.append(utf8(embed_part))\n            file_part = module.css_files()\n            if file_part:\n                if isinstance(file_part, (unicode_type, bytes_type)):\n                    css_files.append(file_part)\n                else:\n                    css_files.extend(file_part)\n            head_part = module.html_head()\n            if head_part:\n                html_heads.append(utf8(head_part))\n            body_part = module.html_body()\n            if body_part:\n                html_bodies.append(utf8(body_part))\n\n        def is_absolute(path):\n            return any(path.startswith(x) for x in [\"/\", \"http:\", \"https:\"])\n        if js_files:\n            # Maintain order of JavaScript files given by modules\n            paths = []\n            unique_paths = set()\n            for path in js_files:\n                if not is_absolute(path):\n                    path = self.static_url(path)\n                if path not in unique_paths:\n                    paths.append(path)\n                    unique_paths.add(path)\n            js = ''.join('<script src=\"' + escape.xhtml_escape(p) +\n                         '\" type=\"text/javascript\"></script>'\n                         for p in paths)\n            sloc = html.rindex(b'</body>')\n            html = html[:sloc] + utf8(js) + b'\\n' + html[sloc:]\n        if js_embed:\n            js = b'<script type=\"text/javascript\">\\n//<![CDATA[\\n' + \\\n                b'\\n'.join(js_embed) + b'\\n//]]>\\n</script>'\n            sloc = html.rindex(b'</body>')\n            html = html[:sloc] + js + b'\\n' + html[sloc:]\n        if css_files:\n            paths = []\n            unique_paths = set()\n            for path in css_files:\n                if not is_absolute(path):\n                    path = self.static_url(path)\n                if path not in unique_paths:\n                    paths.append(path)\n                    unique_paths.add(path)\n            css = ''.join('<link href=\"' + escape.xhtml_escape(p) + '\" '\n                          'type=\"text/css\" rel=\"stylesheet\"/>'\n                          for p in paths)\n            hloc = html.index(b'</head>')\n            html = html[:hloc] + utf8(css) + b'\\n' + html[hloc:]\n        if css_embed:\n            css = b'<style type=\"text/css\">\\n' + b'\\n'.join(css_embed) + \\\n                b'\\n</style>'\n            hloc = html.index(b'</head>')\n            html = html[:hloc] + css + b'\\n' + html[hloc:]\n        if html_heads:\n            hloc = html.index(b'</head>')\n            html = html[:hloc] + b''.join(html_heads) + b'\\n' + html[hloc:]\n        if html_bodies:\n            hloc = html.index(b'</body>')\n            html = html[:hloc] + b''.join(html_bodies) + b'\\n' + html[hloc:]\n        self.finish(html)\n\n    def render_string(self, template_name, **kwargs):\n        \"\"\"Generate the given template with the given arguments.\n\n        We return the generated byte string (in utf8). To generate and\n        write a template as a response, use render() above.\n        \"\"\"\n        # If no template_path is specified, use the path of the calling file\n        template_path = self.get_template_path()\n        if not template_path:\n            frame = sys._getframe(0)\n            web_file = frame.f_code.co_filename\n            while frame.f_code.co_filename == web_file:\n                frame = frame.f_back\n            template_path = os.path.dirname(frame.f_code.co_filename)\n        with RequestHandler._template_loader_lock:\n            if template_path not in RequestHandler._template_loaders:\n                loader = self.create_template_loader(template_path)\n                RequestHandler._template_loaders[template_path] = loader\n            else:\n                loader = RequestHandler._template_loaders[template_path]\n        t = loader.load(template_name)\n        namespace = self.get_template_namespace()\n        namespace.update(kwargs)\n        return t.generate(**namespace)\n\n    def get_template_namespace(self):\n        \"\"\"Returns a dictionary to be used as the default template namespace.\n\n        May be overridden by subclasses to add or modify values.\n\n        The results of this method will be combined with additional\n        defaults in the `tornado.template` module and keyword arguments\n        to `render` or `render_string`.\n        \"\"\"\n        namespace = dict(\n            handler=self,\n            request=self.request,\n            current_user=self.current_user,\n            locale=self.locale,\n            _=self.locale.translate,\n            static_url=self.static_url,\n            xsrf_form_html=self.xsrf_form_html,\n            reverse_url=self.reverse_url\n        )\n        namespace.update(self.ui)\n        return namespace\n\n    def create_template_loader(self, template_path):\n        \"\"\"Returns a new template loader for the given path.\n\n        May be overridden by subclasses.  By default returns a\n        directory-based loader on the given path, using the\n        ``autoescape`` application setting.  If a ``template_loader``\n        application setting is supplied, uses that instead.\n        \"\"\"\n        settings = self.application.settings\n        if \"template_loader\" in settings:\n            return settings[\"template_loader\"]\n        kwargs = {}\n        if \"autoescape\" in settings:\n            # autoescape=None means \"no escaping\", so we have to be sure\n            # to only pass this kwarg if the user asked for it.\n            kwargs[\"autoescape\"] = settings[\"autoescape\"]\n        return template.Loader(template_path, **kwargs)\n\n    def flush(self, include_footers=False, callback=None):\n        \"\"\"Flushes the current output buffer to the network.\n\n        The ``callback`` argument, if given, can be used for flow control:\n        it will be run when all flushed data has been written to the socket.\n        Note that only one flush callback can be outstanding at a time;\n        if another flush occurs before the previous flush's callback\n        has been run, the previous callback will be discarded.\n        \"\"\"\n        if self.application._wsgi:\n            # WSGI applications cannot usefully support flush, so just make\n            # it a no-op (and run the callback immediately).\n            if callback is not None:\n                callback()\n            return\n\n        chunk = b\"\".join(self._write_buffer)\n        self._write_buffer = []\n        if not self._headers_written:\n            self._headers_written = True\n            for transform in self._transforms:\n                self._status_code, self._headers, chunk = \\\n                    transform.transform_first_chunk(\n                        self._status_code, self._headers, chunk, include_footers)\n            headers = self._generate_headers()\n        else:\n            for transform in self._transforms:\n                chunk = transform.transform_chunk(chunk, include_footers)\n            headers = b\"\"\n\n        # Ignore the chunk and only write the headers for HEAD requests\n        if self.request.method == \"HEAD\":\n            if headers:\n                self.request.write(headers, callback=callback)\n            return\n\n        self.request.write(headers + chunk, callback=callback)\n\n    def finish(self, chunk=None):\n        \"\"\"Finishes this response, ending the HTTP request.\"\"\"\n        if self._finished:\n            raise RuntimeError(\"finish() called twice.  May be caused \"\n                               \"by using async operations without the \"\n                               \"@asynchronous decorator.\")\n\n        if chunk is not None:\n            self.write(chunk)\n\n        # Automatically support ETags and add the Content-Length header if\n        # we have not flushed any content yet.\n        if not self._headers_written:\n            if (self._status_code == 200 and\n                self.request.method in (\"GET\", \"HEAD\") and\n                    \"Etag\" not in self._headers):\n                self.set_etag_header()\n                if self.check_etag_header():\n                    self._write_buffer = []\n                    self.set_status(304)\n            if self._status_code == 304:\n                assert not self._write_buffer, \"Cannot send body with 304\"\n                self._clear_headers_for_304()\n            elif \"Content-Length\" not in self._headers:\n                content_length = sum(len(part) for part in self._write_buffer)\n                self.set_header(\"Content-Length\", content_length)\n\n        if hasattr(self.request, \"connection\"):\n            # Now that the request is finished, clear the callback we\n            # set on the IOStream (which would otherwise prevent the\n            # garbage collection of the RequestHandler when there\n            # are keepalive connections)\n            self.request.connection.stream.set_close_callback(None)\n\n        if not self.application._wsgi:\n            self.flush(include_footers=True)\n            self.request.finish()\n            self._log()\n        self._finished = True\n        self.on_finish()\n        # Break up a reference cycle between this handler and the\n        # _ui_module closures to allow for faster GC on CPython.\n        self.ui = None\n\n    def send_error(self, status_code=500, **kwargs):\n        \"\"\"Sends the given HTTP error code to the browser.\n\n        If `flush()` has already been called, it is not possible to send\n        an error, so this method will simply terminate the response.\n        If output has been written but not yet flushed, it will be discarded\n        and replaced with the error page.\n\n        Override `write_error()` to customize the error page that is returned.\n        Additional keyword arguments are passed through to `write_error`.\n        \"\"\"\n        if self._headers_written:\n            gen_log.error(\"Cannot send error response after headers written\")\n            if not self._finished:\n                self.finish()\n            return\n        self.clear()\n\n        reason = None\n        if 'exc_info' in kwargs:\n            exception = kwargs['exc_info'][1]\n            if isinstance(exception, HTTPError) and exception.reason:\n                reason = exception.reason\n        self.set_status(status_code, reason=reason)\n        try:\n            self.write_error(status_code, **kwargs)\n        except Exception:\n            app_log.error(\"Uncaught exception in write_error\", exc_info=True)\n        if not self._finished:\n            self.finish()\n\n    def write_error(self, status_code, **kwargs):\n        \"\"\"Override to implement custom error pages.\n\n        ``write_error`` may call `write`, `render`, `set_header`, etc\n        to produce output as usual.\n\n        If this error was caused by an uncaught exception (including\n        HTTPError), an ``exc_info`` triple will be available as\n        ``kwargs[\"exc_info\"]``.  Note that this exception may not be\n        the \"current\" exception for purposes of methods like\n        ``sys.exc_info()`` or ``traceback.format_exc``.\n\n        For historical reasons, if a method ``get_error_html`` exists,\n        it will be used instead of the default ``write_error`` implementation.\n        ``get_error_html`` returned a string instead of producing output\n        normally, and had different semantics for exception handling.\n        Users of ``get_error_html`` are encouraged to convert their code\n        to override ``write_error`` instead.\n        \"\"\"\n        if hasattr(self, 'get_error_html'):\n            if 'exc_info' in kwargs:\n                exc_info = kwargs.pop('exc_info')\n                kwargs['exception'] = exc_info[1]\n                try:\n                    # Put the traceback into sys.exc_info()\n                    raise_exc_info(exc_info)\n                except Exception:\n                    self.finish(self.get_error_html(status_code, **kwargs))\n            else:\n                self.finish(self.get_error_html(status_code, **kwargs))\n            return\n        if self.settings.get(\"debug\") and \"exc_info\" in kwargs:\n            # in debug mode, try to send a traceback\n            self.set_header('Content-Type', 'text/plain')\n            for line in traceback.format_exception(*kwargs[\"exc_info\"]):\n                self.write(line)\n            self.finish()\n        else:\n            self.finish(\"<html><title>%(code)d: %(message)s</title>\"\n                        \"<body>%(code)d: %(message)s</body></html>\" % {\n                            \"code\": status_code,\n                            \"message\": self._reason,\n                        })\n\n    @property\n    def locale(self):\n        \"\"\"The local for the current session.\n\n        Determined by either `get_user_locale`, which you can override to\n        set the locale based on, e.g., a user preference stored in a\n        database, or `get_browser_locale`, which uses the ``Accept-Language``\n        header.\n        \"\"\"\n        if not hasattr(self, \"_locale\"):\n            self._locale = self.get_user_locale()\n            if not self._locale:\n                self._locale = self.get_browser_locale()\n                assert self._locale\n        return self._locale\n\n    def get_user_locale(self):\n        \"\"\"Override to determine the locale from the authenticated user.\n\n        If None is returned, we fall back to `get_browser_locale()`.\n\n        This method should return a `tornado.locale.Locale` object,\n        most likely obtained via a call like ``tornado.locale.get(\"en\")``\n        \"\"\"\n        return None\n\n    def get_browser_locale(self, default=\"en_US\"):\n        \"\"\"Determines the user's locale from ``Accept-Language`` header.\n\n        See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4\n        \"\"\"\n        if \"Accept-Language\" in self.request.headers:\n            languages = self.request.headers[\"Accept-Language\"].split(\",\")\n            locales = []\n            for language in languages:\n                parts = language.strip().split(\";\")\n                if len(parts) > 1 and parts[1].startswith(\"q=\"):\n                    try:\n                        score = float(parts[1][2:])\n                    except (ValueError, TypeError):\n                        score = 0.0\n                else:\n                    score = 1.0\n                locales.append((parts[0], score))\n            if locales:\n                locales.sort(key=lambda pair: pair[1], reverse=True)\n                codes = [l[0] for l in locales]\n                return locale.get(*codes)\n        return locale.get(default)\n\n    @property\n    def current_user(self):\n        \"\"\"The authenticated user for this request.\n\n        This is a cached version of `get_current_user`, which you can\n        override to set the user based on, e.g., a cookie. If that\n        method is not overridden, this method always returns None.\n\n        We lazy-load the current user the first time this method is called\n        and cache the result after that.\n        \"\"\"\n        if not hasattr(self, \"_current_user\"):\n            self._current_user = self.get_current_user()\n        return self._current_user\n\n    @current_user.setter\n    def current_user(self, value):\n        self._current_user = value\n\n    def get_current_user(self):\n        \"\"\"Override to determine the current user from, e.g., a cookie.\"\"\"\n        return None\n\n    def get_login_url(self):\n        \"\"\"Override to customize the login URL based on the request.\n\n        By default, we use the ``login_url`` application setting.\n        \"\"\"\n        self.require_setting(\"login_url\", \"@tornado.web.authenticated\")\n        return self.application.settings[\"login_url\"]\n\n    def get_template_path(self):\n        \"\"\"Override to customize template path for each handler.\n\n        By default, we use the ``template_path`` application setting.\n        Return None to load templates relative to the calling file.\n        \"\"\"\n        return self.application.settings.get(\"template_path\")\n\n    @property\n    def xsrf_token(self):\n        \"\"\"The XSRF-prevention token for the current user/session.\n\n        To prevent cross-site request forgery, we set an '_xsrf' cookie\n        and include the same '_xsrf' value as an argument with all POST\n        requests. If the two do not match, we reject the form submission\n        as a potential forgery.\n\n        See http://en.wikipedia.org/wiki/Cross-site_request_forgery\n        \"\"\"\n        if not hasattr(self, \"_xsrf_token\"):\n            token = self.get_cookie(\"_xsrf\")\n            if not token:\n                token = binascii.b2a_hex(uuid.uuid4().bytes)\n                expires_days = 30 if self.current_user else None\n                self.set_cookie(\"_xsrf\", token, expires_days=expires_days)\n            self._xsrf_token = token\n        return self._xsrf_token\n\n    def check_xsrf_cookie(self):\n        \"\"\"Verifies that the ``_xsrf`` cookie matches the ``_xsrf`` argument.\n\n        To prevent cross-site request forgery, we set an ``_xsrf``\n        cookie and include the same value as a non-cookie\n        field with all ``POST`` requests. If the two do not match, we\n        reject the form submission as a potential forgery.\n\n        The ``_xsrf`` value may be set as either a form field named ``_xsrf``\n        or in a custom HTTP header named ``X-XSRFToken`` or ``X-CSRFToken``\n        (the latter is accepted for compatibility with Django).\n\n        See http://en.wikipedia.org/wiki/Cross-site_request_forgery\n\n        Prior to release 1.1.1, this check was ignored if the HTTP header\n        ``X-Requested-With: XMLHTTPRequest`` was present.  This exception\n        has been shown to be insecure and has been removed.  For more\n        information please see\n        http://www.djangoproject.com/weblog/2011/feb/08/security/\n        http://weblog.rubyonrails.org/2011/2/8/csrf-protection-bypass-in-ruby-on-rails\n        \"\"\"\n        token = (self.get_argument(\"_xsrf\", None) or\n                 self.request.headers.get(\"X-Xsrftoken\") or\n                 self.request.headers.get(\"X-Csrftoken\"))\n        if not token:\n            raise HTTPError(403, \"'_xsrf' argument missing from POST\")\n        if self.xsrf_token != token:\n            raise HTTPError(403, \"XSRF cookie does not match POST argument\")\n\n    def xsrf_form_html(self):\n        \"\"\"An HTML ``<input/>`` element to be included with all POST forms.\n\n        It defines the ``_xsrf`` input value, which we check on all POST\n        requests to prevent cross-site request forgery. If you have set\n        the ``xsrf_cookies`` application setting, you must include this\n        HTML within all of your HTML forms.\n\n        In a template, this method should be called with ``{% module\n        xsrf_form_html() %}``\n\n        See `check_xsrf_cookie()` above for more information.\n        \"\"\"\n        return '<input type=\"hidden\" name=\"_xsrf\" value=\"' + \\\n            escape.xhtml_escape(self.xsrf_token) + '\"/>'\n\n    def static_url(self, path, include_host=None, **kwargs):\n        \"\"\"Returns a static URL for the given relative static file path.\n\n        This method requires you set the ``static_path`` setting in your\n        application (which specifies the root directory of your static\n        files).\n\n        This method returns a versioned url (by default appending\n        ``?v=<signature>``), which allows the static files to be\n        cached indefinitely.  This can be disabled by passing\n        ``include_version=False`` (in the default implementation;\n        other static file implementations are not required to support\n        this, but they may support other options).\n\n        By default this method returns URLs relative to the current\n        host, but if ``include_host`` is true the URL returned will be\n        absolute.  If this handler has an ``include_host`` attribute,\n        that value will be used as the default for all `static_url`\n        calls that do not pass ``include_host`` as a keyword argument.\n\n        \"\"\"\n        self.require_setting(\"static_path\", \"static_url\")\n        get_url = self.settings.get(\"static_handler_class\",\n                                    StaticFileHandler).make_static_url\n\n        if include_host is None:\n            include_host = getattr(self, \"include_host\", False)\n\n        if include_host:\n            base = self.request.protocol + \"://\" + self.request.host\n        else:\n            base = \"\"\n\n        return base + get_url(self.settings, path, **kwargs)\n\n    def async_callback(self, callback, *args, **kwargs):\n        \"\"\"Obsolete - catches exceptions from the wrapped function.\n\n        This function is unnecessary since Tornado 1.1.\n        \"\"\"\n        if callback is None:\n            return None\n        if args or kwargs:\n            callback = functools.partial(callback, *args, **kwargs)\n\n        def wrapper(*args, **kwargs):\n            try:\n                return callback(*args, **kwargs)\n            except Exception as e:\n                if self._headers_written:\n                    app_log.error(\"Exception after headers written\",\n                                  exc_info=True)\n                else:\n                    self._handle_request_exception(e)\n        return wrapper\n\n    def require_setting(self, name, feature=\"this feature\"):\n        \"\"\"Raises an exception if the given app setting is not defined.\"\"\"\n        if not self.application.settings.get(name):\n            raise Exception(\"You must define the '%s' setting in your \"\n                            \"application to use %s\" % (name, feature))\n\n    def reverse_url(self, name, *args):\n        \"\"\"Alias for `Application.reverse_url`.\"\"\"\n        return self.application.reverse_url(name, *args)\n\n    def compute_etag(self):\n        \"\"\"Computes the etag header to be used for this request.\n\n        By default uses a hash of the content written so far.\n\n        May be overridden to provide custom etag implementations,\n        or may return None to disable tornado's default etag support.\n        \"\"\"\n        hasher = hashlib.sha1()\n        for part in self._write_buffer:\n            hasher.update(part)\n        return '\"%s\"' % hasher.hexdigest()\n\n    def set_etag_header(self):\n        \"\"\"Sets the response's Etag header using ``self.compute_etag()``.\n\n        Note: no header will be set if ``compute_etag()`` returns ``None``.\n\n        This method is called automatically when the request is finished.\n        \"\"\"\n        etag = self.compute_etag()\n        if etag is not None:\n            self.set_header(\"Etag\", etag)\n\n    def check_etag_header(self):\n        \"\"\"Checks the ``Etag`` header against requests's ``If-None-Match``.\n\n        Returns ``True`` if the request's Etag matches and a 304 should be\n        returned. For example::\n\n            self.set_etag_header()\n            if self.check_etag_header():\n                self.set_status(304)\n                return\n\n        This method is called automatically when the request is finished,\n        but may be called earlier for applications that override\n        `compute_etag` and want to do an early check for ``If-None-Match``\n        before completing the request.  The ``Etag`` header should be set\n        (perhaps with `set_etag_header`) before calling this method.\n        \"\"\"\n        etag = self._headers.get(\"Etag\")\n        inm = utf8(self.request.headers.get(\"If-None-Match\", \"\"))\n        return bool(etag and inm and inm.find(etag) >= 0)\n\n    def _stack_context_handle_exception(self, type, value, traceback):\n        try:\n            # For historical reasons _handle_request_exception only takes\n            # the exception value instead of the full triple,\n            # so re-raise the exception to ensure that it's in\n            # sys.exc_info()\n            raise_exc_info((type, value, traceback))\n        except Exception:\n            self._handle_request_exception(value)\n        return True\n\n    def _execute(self, transforms, *args, **kwargs):\n        \"\"\"Executes this request with the given output transforms.\"\"\"\n        self._transforms = transforms\n        try:\n            if self.request.method not in self.SUPPORTED_METHODS:\n                raise HTTPError(405)\n            self.path_args = [self.decode_argument(arg) for arg in args]\n            self.path_kwargs = dict((k, self.decode_argument(v, name=k))\n                                    for (k, v) in kwargs.items())\n            # If XSRF cookies are turned on, reject form submissions without\n            # the proper cookie\n            if self.request.method not in (\"GET\", \"HEAD\", \"OPTIONS\") and \\\n                    self.application.settings.get(\"xsrf_cookies\"):\n                self.check_xsrf_cookie()\n            self._when_complete(self.prepare(), self._execute_method)\n        except Exception as e:\n            self._handle_request_exception(e)\n\n    def _when_complete(self, result, callback):\n        try:\n            if result is None:\n                callback()\n            elif isinstance(result, Future):\n                if result.done():\n                    if result.result() is not None:\n                        raise ValueError('Expected None, got %r' % result.result())\n                    callback()\n                else:\n                    # Delayed import of IOLoop because it's not available\n                    # on app engine\n                    from tornado.ioloop import IOLoop\n                    IOLoop.current().add_future(\n                        result, functools.partial(self._when_complete,\n                                                  callback=callback))\n            else:\n                raise ValueError(\"Expected Future or None, got %r\" % result)\n        except Exception as e:\n            self._handle_request_exception(e)\n\n    def _execute_method(self):\n        if not self._finished:\n            method = getattr(self, self.request.method.lower())\n            self._when_complete(method(*self.path_args, **self.path_kwargs),\n                                self._execute_finish)\n\n    def _execute_finish(self):\n        if self._auto_finish and not self._finished:\n            self.finish()\n\n    def _generate_headers(self):\n        reason = self._reason\n        lines = [utf8(self.request.version + \" \" +\n                      str(self._status_code) +\n                      \" \" + reason)]\n        lines.extend([utf8(n) + b\": \" + utf8(v) for n, v in self._headers.get_all()])\n\n        if hasattr(self, \"_new_cookie\"):\n            for cookie in self._new_cookie.values():\n                lines.append(utf8(\"Set-Cookie: \" + cookie.OutputString(None)))\n        return b\"\\r\\n\".join(lines) + b\"\\r\\n\\r\\n\"\n\n    def _log(self):\n        \"\"\"Logs the current request.\n\n        Sort of deprecated since this functionality was moved to the\n        Application, but left in place for the benefit of existing apps\n        that have overridden this method.\n        \"\"\"\n        self.application.log_request(self)\n\n    def _request_summary(self):\n        return self.request.method + \" \" + self.request.uri + \\\n            \" (\" + self.request.remote_ip + \")\"\n\n    def _handle_request_exception(self, e):\n        self.log_exception(*sys.exc_info())\n        if self._finished:\n            # Extra errors after the request has been finished should\n            # be logged, but there is no reason to continue to try and\n            # send a response.\n            return\n        if isinstance(e, HTTPError):\n            if e.status_code not in httputil.responses and not e.reason:\n                gen_log.error(\"Bad HTTP status code: %d\", e.status_code)\n                self.send_error(500, exc_info=sys.exc_info())\n            else:\n                self.send_error(e.status_code, exc_info=sys.exc_info())\n        else:\n            self.send_error(500, exc_info=sys.exc_info())\n\n    def log_exception(self, typ, value, tb):\n        \"\"\"Override to customize logging of uncaught exceptions.\n\n        By default logs instances of `HTTPError` as warnings without\n        stack traces (on the ``tornado.general`` logger), and all\n        other exceptions as errors with stack traces (on the\n        ``tornado.application`` logger).\n\n        .. versionadded:: 3.1\n        \"\"\"\n        if isinstance(value, HTTPError):\n            if value.log_message:\n                format = \"%d %s: \" + value.log_message\n                args = ([value.status_code, self._request_summary()] +\n                        list(value.args))\n                gen_log.warning(format, *args)\n        else:\n            app_log.error(\"Uncaught exception %s\\n%r\", self._request_summary(),\n                          self.request, exc_info=(typ, value, tb))\n\n    def _ui_module(self, name, module):\n        def render(*args, **kwargs):\n            if not hasattr(self, \"_active_modules\"):\n                self._active_modules = {}\n            if name not in self._active_modules:\n                self._active_modules[name] = module(self)\n            rendered = self._active_modules[name].render(*args, **kwargs)\n            return rendered\n        return render\n\n    def _ui_method(self, method):\n        return lambda *args, **kwargs: method(self, *args, **kwargs)\n\n    def _clear_headers_for_304(self):\n        # 304 responses should not contain entity headers (defined in\n        # http://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html#sec7.1)\n        # not explicitly allowed by\n        # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5\n        headers = [\"Allow\", \"Content-Encoding\", \"Content-Language\",\n                   \"Content-Length\", \"Content-MD5\", \"Content-Range\",\n                   \"Content-Type\", \"Last-Modified\"]\n        for h in headers:\n            self.clear_header(h)\n\n\ndef asynchronous(method):\n    \"\"\"Wrap request handler methods with this if they are asynchronous.\n\n    This decorator is unnecessary if the method is also decorated with\n    ``@gen.coroutine`` (it is legal but unnecessary to use the two\n    decorators together, in which case ``@asynchronous`` must be\n    first).\n\n    This decorator should only be applied to the :ref:`HTTP verb\n    methods <verbs>`; its behavior is undefined for any other method.\n    This decorator does not *make* a method asynchronous; it tells\n    the framework that the method *is* asynchronous.  For this decorator\n    to be useful the method must (at least sometimes) do something\n    asynchronous.\n\n    If this decorator is given, the response is not finished when the\n    method returns. It is up to the request handler to call\n    `self.finish() <RequestHandler.finish>` to finish the HTTP\n    request. Without this decorator, the request is automatically\n    finished when the ``get()`` or ``post()`` method returns. Example::\n\n       class MyRequestHandler(web.RequestHandler):\n           @web.asynchronous\n           def get(self):\n              http = httpclient.AsyncHTTPClient()\n              http.fetch(\"http://friendfeed.com/\", self._on_download)\n\n           def _on_download(self, response):\n              self.write(\"Downloaded!\")\n              self.finish()\n\n    .. versionadded:: 3.1\n       The ability to use ``@gen.coroutine`` without ``@asynchronous``.\n    \"\"\"\n    # Delay the IOLoop import because it's not available on app engine.\n    from tornado.ioloop import IOLoop\n    @functools.wraps(method)\n    def wrapper(self, *args, **kwargs):\n        if self.application._wsgi:\n            raise Exception(\"@asynchronous is not supported for WSGI apps\")\n        self._auto_finish = False\n        with stack_context.ExceptionStackContext(\n                self._stack_context_handle_exception):\n            result = method(self, *args, **kwargs)\n            if isinstance(result, Future):\n                # If @asynchronous is used with @gen.coroutine, (but\n                # not @gen.engine), we can automatically finish the\n                # request when the future resolves.  Additionally,\n                # the Future will swallow any exceptions so we need\n                # to throw them back out to the stack context to finish\n                # the request.\n                def future_complete(f):\n                    f.result()\n                    if not self._finished:\n                        self.finish()\n                IOLoop.current().add_future(result, future_complete)\n            return result\n    return wrapper\n\n\ndef removeslash(method):\n    \"\"\"Use this decorator to remove trailing slashes from the request path.\n\n    For example, a request to ``/foo/`` would redirect to ``/foo`` with this\n    decorator. Your request handler mapping should use a regular expression\n    like ``r'/foo/*'`` in conjunction with using the decorator.\n    \"\"\"\n    @functools.wraps(method)\n    def wrapper(self, *args, **kwargs):\n        if self.request.path.endswith(\"/\"):\n            if self.request.method in (\"GET\", \"HEAD\"):\n                uri = self.request.path.rstrip(\"/\")\n                if uri:  # don't try to redirect '/' to ''\n                    if self.request.query:\n                        uri += \"?\" + self.request.query\n                    self.redirect(uri, permanent=True)\n                    return\n            else:\n                raise HTTPError(404)\n        return method(self, *args, **kwargs)\n    return wrapper\n\n\ndef addslash(method):\n    \"\"\"Use this decorator to add a missing trailing slash to the request path.\n\n    For example, a request to ``/foo`` would redirect to ``/foo/`` with this\n    decorator. Your request handler mapping should use a regular expression\n    like ``r'/foo/?'`` in conjunction with using the decorator.\n    \"\"\"\n    @functools.wraps(method)\n    def wrapper(self, *args, **kwargs):\n        if not self.request.path.endswith(\"/\"):\n            if self.request.method in (\"GET\", \"HEAD\"):\n                uri = self.request.path + \"/\"\n                if self.request.query:\n                    uri += \"?\" + self.request.query\n                self.redirect(uri, permanent=True)\n                return\n            raise HTTPError(404)\n        return method(self, *args, **kwargs)\n    return wrapper\n\n\nclass Application(object):\n    \"\"\"A collection of request handlers that make up a web application.\n\n    Instances of this class are callable and can be passed directly to\n    HTTPServer to serve the application::\n\n        application = web.Application([\n            (r\"/\", MainPageHandler),\n        ])\n        http_server = httpserver.HTTPServer(application)\n        http_server.listen(8080)\n        ioloop.IOLoop.instance().start()\n\n    The constructor for this class takes in a list of `URLSpec` objects\n    or (regexp, request_class) tuples. When we receive requests, we\n    iterate over the list in order and instantiate an instance of the\n    first request class whose regexp matches the request path.\n\n    Each tuple can contain an optional third element, which should be\n    a dictionary if it is present. That dictionary is passed as\n    keyword arguments to the contructor of the handler. This pattern\n    is used for the `StaticFileHandler` in this example (note that a\n    `StaticFileHandler` can be installed automatically with the\n    static_path setting described below)::\n\n        application = web.Application([\n            (r\"/static/(.*)\", web.StaticFileHandler, {\"path\": \"/var/www\"}),\n        ])\n\n    We support virtual hosts with the `add_handlers` method, which takes in\n    a host regular expression as the first argument::\n\n        application.add_handlers(r\"www\\.myhost\\.com\", [\n            (r\"/article/([0-9]+)\", ArticleHandler),\n        ])\n\n    You can serve static files by sending the ``static_path`` setting\n    as a keyword argument. We will serve those files from the\n    ``/static/`` URI (this is configurable with the\n    ``static_url_prefix`` setting), and we will serve ``/favicon.ico``\n    and ``/robots.txt`` from the same directory.  A custom subclass of\n    `StaticFileHandler` can be specified with the\n    ``static_handler_class`` setting.\n    \"\"\"\n    def __init__(self, handlers=None, default_host=\"\", transforms=None,\n                 wsgi=False, **settings):\n        if transforms is None:\n            self.transforms = []\n            if settings.get(\"gzip\"):\n                self.transforms.append(GZipContentEncoding)\n            self.transforms.append(ChunkedTransferEncoding)\n        else:\n            self.transforms = transforms\n        self.handlers = []\n        self.named_handlers = {}\n        self.default_host = default_host\n        self.settings = settings\n        self.ui_modules = {'linkify': _linkify,\n                           'xsrf_form_html': _xsrf_form_html,\n                           'Template': TemplateModule,\n                           }\n        self.ui_methods = {}\n        self._wsgi = wsgi\n        self._load_ui_modules(settings.get(\"ui_modules\", {}))\n        self._load_ui_methods(settings.get(\"ui_methods\", {}))\n        if self.settings.get(\"static_path\"):\n            path = self.settings[\"static_path\"]\n            handlers = list(handlers or [])\n            static_url_prefix = settings.get(\"static_url_prefix\",\n                                             \"/static/\")\n            static_handler_class = settings.get(\"static_handler_class\",\n                                                StaticFileHandler)\n            static_handler_args = settings.get(\"static_handler_args\", {})\n            static_handler_args['path'] = path\n            for pattern in [re.escape(static_url_prefix) + r\"(.*)\",\n                            r\"/(favicon\\.ico)\", r\"/(robots\\.txt)\"]:\n                handlers.insert(0, (pattern, static_handler_class,\n                                    static_handler_args))\n        if handlers:\n            self.add_handlers(\".*$\", handlers)\n\n        # Automatically reload modified modules\n        if self.settings.get(\"debug\") and not wsgi:\n            from tornado import autoreload\n            autoreload.start()\n\n    def listen(self, port, address=\"\", **kwargs):\n        \"\"\"Starts an HTTP server for this application on the given port.\n\n        This is a convenience alias for creating an `.HTTPServer`\n        object and calling its listen method.  Keyword arguments not\n        supported by `HTTPServer.listen <.TCPServer.listen>` are passed to the\n        `.HTTPServer` constructor.  For advanced uses\n        (e.g. multi-process mode), do not use this method; create an\n        `.HTTPServer` and call its\n        `.TCPServer.bind`/`.TCPServer.start` methods directly.\n\n        Note that after calling this method you still need to call\n        ``IOLoop.instance().start()`` to start the server.\n        \"\"\"\n        # import is here rather than top level because HTTPServer\n        # is not importable on appengine\n        from tornado.httpserver import HTTPServer\n        server = HTTPServer(self, **kwargs)\n        server.listen(port, address)\n\n    def add_handlers(self, host_pattern, host_handlers):\n        \"\"\"Appends the given handlers to our handler list.\n\n        Host patterns are processed sequentially in the order they were\n        added. All matching patterns will be considered.\n        \"\"\"\n        if not host_pattern.endswith(\"$\"):\n            host_pattern += \"$\"\n        handlers = []\n        # The handlers with the wildcard host_pattern are a special\n        # case - they're added in the constructor but should have lower\n        # precedence than the more-precise handlers added later.\n        # If a wildcard handler group exists, it should always be last\n        # in the list, so insert new groups just before it.\n        if self.handlers and self.handlers[-1][0].pattern == '.*$':\n            self.handlers.insert(-1, (re.compile(host_pattern), handlers))\n        else:\n            self.handlers.append((re.compile(host_pattern), handlers))\n\n        for spec in host_handlers:\n            if isinstance(spec, (tuple, list)):\n                assert len(spec) in (2, 3)\n                pattern = spec[0]\n                handler = spec[1]\n\n                if isinstance(handler, str):\n                    # import the Module and instantiate the class\n                    # Must be a fully qualified name (module.ClassName)\n                    handler = import_object(handler)\n\n                if len(spec) == 3:\n                    kwargs = spec[2]\n                else:\n                    kwargs = {}\n                spec = URLSpec(pattern, handler, kwargs)\n            handlers.append(spec)\n            if spec.name:\n                if spec.name in self.named_handlers:\n                    app_log.warning(\n                        \"Multiple handlers named %s; replacing previous value\",\n                        spec.name)\n                self.named_handlers[spec.name] = spec\n\n    def add_transform(self, transform_class):\n        self.transforms.append(transform_class)\n\n    def _get_host_handlers(self, request):\n        host = request.host.lower().split(':')[0]\n        matches = []\n        for pattern, handlers in self.handlers:\n            if pattern.match(host):\n                matches.extend(handlers)\n        # Look for default host if not behind load balancer (for debugging)\n        if not matches and \"X-Real-Ip\" not in request.headers:\n            for pattern, handlers in self.handlers:\n                if pattern.match(self.default_host):\n                    matches.extend(handlers)\n        return matches or None\n\n    def _load_ui_methods(self, methods):\n        if isinstance(methods, types.ModuleType):\n            self._load_ui_methods(dict((n, getattr(methods, n))\n                                       for n in dir(methods)))\n        elif isinstance(methods, list):\n            for m in methods:\n                self._load_ui_methods(m)\n        else:\n            for name, fn in methods.items():\n                if not name.startswith(\"_\") and hasattr(fn, \"__call__\") \\\n                        and name[0].lower() == name[0]:\n                    self.ui_methods[name] = fn\n\n    def _load_ui_modules(self, modules):\n        if isinstance(modules, types.ModuleType):\n            self._load_ui_modules(dict((n, getattr(modules, n))\n                                       for n in dir(modules)))\n        elif isinstance(modules, list):\n            for m in modules:\n                self._load_ui_modules(m)\n        else:\n            assert isinstance(modules, dict)\n            for name, cls in modules.items():\n                try:\n                    if issubclass(cls, UIModule):\n                        self.ui_modules[name] = cls\n                except TypeError:\n                    pass\n\n    def __call__(self, request):\n        \"\"\"Called by HTTPServer to execute the request.\"\"\"\n        transforms = [t(request) for t in self.transforms]\n        handler = None\n        args = []\n        kwargs = {}\n        handlers = self._get_host_handlers(request)\n        if not handlers:\n            handler = RedirectHandler(\n                self, request, url=\"http://\" + self.default_host + \"/\")\n        else:\n            for spec in handlers:\n                match = spec.regex.match(request.path)\n                if match:\n                    handler = spec.handler_class(self, request, **spec.kwargs)\n                    if spec.regex.groups:\n                        # None-safe wrapper around url_unescape to handle\n                        # unmatched optional groups correctly\n                        def unquote(s):\n                            if s is None:\n                                return s\n                            return escape.url_unescape(s, encoding=None,\n                                                       plus=False)\n                        # Pass matched groups to the handler.  Since\n                        # match.groups() includes both named and unnamed groups,\n                        # we want to use either groups or groupdict but not both.\n                        # Note that args are passed as bytes so the handler can\n                        # decide what encoding to use.\n\n                        if spec.regex.groupindex:\n                            kwargs = dict(\n                                (str(k), unquote(v))\n                                for (k, v) in match.groupdict().items())\n                        else:\n                            args = [unquote(s) for s in match.groups()]\n                    break\n            if not handler:\n                handler = ErrorHandler(self, request, status_code=404)\n\n        # In debug mode, re-compile templates and reload static files on every\n        # request so you don't need to restart to see changes\n        if self.settings.get(\"debug\"):\n            with RequestHandler._template_loader_lock:\n                for loader in RequestHandler._template_loaders.values():\n                    loader.reset()\n            StaticFileHandler.reset()\n\n        handler._execute(transforms, *args, **kwargs)\n        return handler\n\n    def reverse_url(self, name, *args):\n        \"\"\"Returns a URL path for handler named ``name``\n\n        The handler must be added to the application as a named `URLSpec`.\n\n        Args will be substituted for capturing groups in the `URLSpec` regex.\n        They will be converted to strings if necessary, encoded as utf8,\n        and url-escaped.\n        \"\"\"\n        if name in self.named_handlers:\n            return self.named_handlers[name].reverse(*args)\n        raise KeyError(\"%s not found in named urls\" % name)\n\n    def log_request(self, handler):\n        \"\"\"Writes a completed HTTP request to the logs.\n\n        By default writes to the python root logger.  To change\n        this behavior either subclass Application and override this method,\n        or pass a function in the application settings dictionary as\n        ``log_function``.\n        \"\"\"\n        if \"log_function\" in self.settings:\n            self.settings[\"log_function\"](handler)\n            return\n        if handler.get_status() < 400:\n            log_method = access_log.info\n        elif handler.get_status() < 500:\n            log_method = access_log.warning\n        else:\n            log_method = access_log.error\n        request_time = 1000.0 * handler.request.request_time()\n        log_method(\"%d %s %.2fms\", handler.get_status(),\n                   handler._request_summary(), request_time)\n\n\nclass HTTPError(Exception):\n    \"\"\"An exception that will turn into an HTTP error response.\n\n    Raising an `HTTPError` is a convenient alternative to calling\n    `RequestHandler.send_error` since it automatically ends the\n    current function.\n\n    :arg int status_code: HTTP status code.  Must be listed in\n        `httplib.responses <http.client.responses>` unless the ``reason``\n        keyword argument is given.\n    :arg string log_message: Message to be written to the log for this error\n        (will not be shown to the user unless the `Application` is in debug\n        mode).  May contain ``%s``-style placeholders, which will be filled\n        in with remaining positional parameters.\n    :arg string reason: Keyword-only argument.  The HTTP \"reason\" phrase\n        to pass in the status line along with ``status_code``.  Normally\n        determined automatically from ``status_code``, but can be used\n        to use a non-standard numeric code.\n    \"\"\"\n    def __init__(self, status_code, log_message=None, *args, **kwargs):\n        self.status_code = status_code\n        self.log_message = log_message\n        self.args = args\n        self.reason = kwargs.get('reason', None)\n\n    def __str__(self):\n        message = \"HTTP %d: %s\" % (\n            self.status_code,\n            self.reason or httputil.responses.get(self.status_code, 'Unknown'))\n        if self.log_message:\n            return message + \" (\" + (self.log_message % self.args) + \")\"\n        else:\n            return message\n\n\nclass MissingArgumentError(HTTPError):\n    \"\"\"Exception raised by `RequestHandler.get_argument`.\n\n    This is a subclass of `HTTPError`, so if it is uncaught a 400 response\n    code will be used instead of 500 (and a stack trace will not be logged).\n\n    .. versionadded:: 3.1\n    \"\"\"\n    def __init__(self, arg_name):\n        super(MissingArgumentError, self).__init__(\n            400, 'Missing argument %s' % arg_name)\n        self.arg_name = arg_name\n\n\nclass ErrorHandler(RequestHandler):\n    \"\"\"Generates an error response with ``status_code`` for all requests.\"\"\"\n    def initialize(self, status_code):\n        self.set_status(status_code)\n\n    def prepare(self):\n        raise HTTPError(self._status_code)\n\n    def check_xsrf_cookie(self):\n        # POSTs to an ErrorHandler don't actually have side effects,\n        # so we don't need to check the xsrf token.  This allows POSTs\n        # to the wrong url to return a 404 instead of 403.\n        pass\n\n\nclass RedirectHandler(RequestHandler):\n    \"\"\"Redirects the client to the given URL for all GET requests.\n\n    You should provide the keyword argument ``url`` to the handler, e.g.::\n\n        application = web.Application([\n            (r\"/oldpath\", web.RedirectHandler, {\"url\": \"/newpath\"}),\n        ])\n    \"\"\"\n    def initialize(self, url, permanent=True):\n        self._url = url\n        self._permanent = permanent\n\n    def get(self):\n        self.redirect(self._url, permanent=self._permanent)\n\n\nclass StaticFileHandler(RequestHandler):\n    \"\"\"A simple handler that can serve static content from a directory.\n\n    A `StaticFileHandler` is configured automatically if you pass the\n    ``static_path`` keyword argument to `Application`.  This handler\n    can be customized with the ``static_url_prefix``, ``static_handler_class``,\n    and ``static_handler_args`` settings.\n\n    To map an additional path to this handler for a static data directory\n    you would add a line to your application like::\n\n        application = web.Application([\n            (r\"/content/(.*)\", web.StaticFileHandler, {\"path\": \"/var/www\"}),\n        ])\n\n    The handler constructor requires a ``path`` argument, which specifies the\n    local root directory of the content to be served.\n\n    Note that a capture group in the regex is required to parse the value for\n    the ``path`` argument to the get() method (different than the constructor\n    argument above); see `URLSpec` for details.\n\n    To maximize the effectiveness of browser caching, this class supports\n    versioned urls (by default using the argument ``?v=``).  If a version\n    is given, we instruct the browser to cache this file indefinitely.\n    `make_static_url` (also available as `RequestHandler.static_url`) can\n    be used to construct a versioned url.\n\n    This handler is intended primarily for use in development and light-duty\n    file serving; for heavy traffic it will be more efficient to use\n    a dedicated static file server (such as nginx or Apache).  We support\n    the HTTP ``Accept-Ranges`` mechanism to return partial content (because\n    some browsers require this functionality to be present to seek in\n    HTML5 audio or video), but this handler should not be used with\n    files that are too large to fit comfortably in memory.\n\n    **Subclassing notes**\n\n    This class is designed to be extensible by subclassing, but because\n    of the way static urls are generated with class methods rather than\n    instance methods, the inheritance patterns are somewhat unusual.\n    Be sure to use the ``@classmethod`` decorator when overriding a\n    class method.  Instance methods may use the attributes ``self.path``\n    ``self.absolute_path``, and ``self.modified``.\n\n    To change the way static urls are generated (e.g. to match the behavior\n    of another server or CDN), override `make_static_url`, `parse_url_path`,\n    `get_cache_time`, and/or `get_version`.\n\n    To replace all interaction with the filesystem (e.g. to serve\n    static content from a database), override `get_content`,\n    `get_content_size`, `get_modified_time`, `get_absolute_path`, and\n    `validate_absolute_path`.\n\n    .. versionchanged:: 3.1\n       Many of the methods for subclasses were added in Tornado 3.1.\n    \"\"\"\n    CACHE_MAX_AGE = 86400 * 365 * 10  # 10 years\n\n    _static_hashes = {}\n    _lock = threading.Lock()  # protects _static_hashes\n\n    def initialize(self, path, default_filename=None):\n        self.root = path\n        self.default_filename = default_filename\n\n    @classmethod\n    def reset(cls):\n        with cls._lock:\n            cls._static_hashes = {}\n\n    def head(self, path):\n        self.get(path, include_body=False)\n\n    def get(self, path, include_body=True):\n        # Set up our path instance variables.\n        self.path = self.parse_url_path(path)\n        del path  # make sure we don't refer to path instead of self.path again\n        absolute_path = self.get_absolute_path(self.root, self.path)\n        self.absolute_path = self.validate_absolute_path(\n            self.root, absolute_path)\n        if self.absolute_path is None:\n            return\n\n        self.modified = self.get_modified_time()\n        self.set_headers()\n\n        if self.should_return_304():\n            self.set_status(304)\n            return\n\n        request_range = None\n        range_header = self.request.headers.get(\"Range\")\n        if range_header:\n            # As per RFC 2616 14.16, if an invalid Range header is specified,\n            # the request will be treated as if the header didn't exist.\n            request_range = httputil._parse_request_range(range_header)\n\n        if request_range:\n            start, end = request_range\n            size = self.get_content_size()\n            if (start is not None and start >= size) or end == 0:\n                # As per RFC 2616 14.35.1, a range is not satisfiable only: if\n                # the first requested byte is equal to or greater than the\n                # content, or when a suffix with length 0 is specified\n                self.set_status(416)  # Range Not Satisfiable\n                self.set_header(\"Content-Type\", \"text/plain\")\n                self.set_header(\"Content-Range\", \"bytes */%s\" %(size, ))\n                return\n            if start is not None and start < 0:\n                start += size\n            if end is not None and end > size:\n                # Clients sometimes blindly use a large range to limit their\n                # download size; cap the endpoint at the actual file size.\n                end = size\n            # Note: only return HTTP 206 if less than the entire range has been\n            # requested. Not only is this semantically correct, but Chrome\n            # refuses to play audio if it gets an HTTP 206 in response to\n            # ``Range: bytes=0-``.\n            if size != (end or size) - (start or 0):\n                self.set_status(206)  # Partial Content\n                self.set_header(\"Content-Range\",\n                                httputil._get_content_range(start, end, size))\n        else:\n            start = end = None\n        content = self.get_content(self.absolute_path, start, end)\n        if isinstance(content, bytes_type):\n            content = [content]\n        content_length = 0\n        for chunk in content:\n            if include_body:\n                self.write(chunk)\n            else:\n                content_length += len(chunk)\n        if not include_body:\n            assert self.request.method == \"HEAD\"\n            self.set_header(\"Content-Length\", content_length)\n\n    def compute_etag(self):\n        \"\"\"Sets the ``Etag`` header based on static url version.\n\n        This allows efficient ``If-None-Match`` checks against cached\n        versions, and sends the correct ``Etag`` for a partial response\n        (i.e. the same ``Etag`` as the full file).\n\n        .. versionadded:: 3.1\n        \"\"\"\n        version_hash = self._get_cached_version(self.absolute_path)\n        if not version_hash:\n            return None\n        return '\"%s\"' % (version_hash, )\n\n    def set_headers(self):\n        \"\"\"Sets the content and caching headers on the response.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        self.set_header(\"Accept-Ranges\", \"bytes\")\n        self.set_etag_header()\n\n        if self.modified is not None:\n            self.set_header(\"Last-Modified\", self.modified)\n\n        content_type = self.get_content_type()\n        if content_type:\n            self.set_header(\"Content-Type\", content_type)\n\n        cache_time = self.get_cache_time(self.path, self.modified, content_type)\n        if cache_time > 0:\n            self.set_header(\"Expires\", datetime.datetime.utcnow() +\n                            datetime.timedelta(seconds=cache_time))\n            self.set_header(\"Cache-Control\", \"max-age=\" + str(cache_time))\n\n        self.set_extra_headers(self.path)\n\n    def should_return_304(self):\n        \"\"\"Returns True if the headers indicate that we should return 304.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        if self.check_etag_header():\n            return True\n\n        # Check the If-Modified-Since, and don't send the result if the\n        # content has not been modified\n        ims_value = self.request.headers.get(\"If-Modified-Since\")\n        if ims_value is not None:\n            date_tuple = email.utils.parsedate(ims_value)\n            if date_tuple is not None:\n                if_since = datetime.datetime(*date_tuple[:6])\n                if if_since >= self.modified:\n                    return True\n\n        return False\n\n    @classmethod\n    def get_absolute_path(cls, root, path):\n        \"\"\"Returns the absolute location of ``path`` relative to ``root``.\n\n        ``root`` is the path configured for this `StaticFileHandler`\n        (in most cases the ``static_path`` `Application` setting).\n\n        This class method may be overridden in subclasses.  By default\n        it returns a filesystem path, but other strings may be used\n        as long as they are unique and understood by the subclass's\n        overridden `get_content`.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        abspath = os.path.abspath(os.path.join(root, path))\n        return abspath\n\n    def validate_absolute_path(self, root, absolute_path):\n        \"\"\"Validate and return the absolute path.\n\n        ``root`` is the configured path for the `StaticFileHandler`,\n        and ``path`` is the result of `get_absolute_path`\n\n        This is an instance method called during request processing,\n        so it may raise `HTTPError` or use methods like\n        `RequestHandler.redirect` (return None after redirecting to\n        halt further processing).  This is where 404 errors for missing files\n        are generated.\n\n        This method may modify the path before returning it, but note that\n        any such modifications will not be understood by `make_static_url`.\n\n        In instance methods, this method's result is available as\n        ``self.absolute_path``.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        root = os.path.abspath(root)\n        # os.path.abspath strips a trailing /\n        # it needs to be temporarily added back for requests to root/\n        if not (absolute_path + os.path.sep).startswith(root):\n            raise HTTPError(403, \"%s is not in root static directory\",\n                            self.path)\n        if (os.path.isdir(absolute_path) and\n                self.default_filename is not None):\n            # need to look at the request.path here for when path is empty\n            # but there is some prefix to the path that was already\n            # trimmed by the routing\n            if not self.request.path.endswith(\"/\"):\n                self.redirect(self.request.path + \"/\", permanent=True)\n                return\n            absolute_path = os.path.join(absolute_path, self.default_filename)\n        if not os.path.exists(absolute_path):\n            raise HTTPError(404)\n        if not os.path.isfile(absolute_path):\n            raise HTTPError(403, \"%s is not a file\", self.path)\n        return absolute_path\n\n    @classmethod\n    def get_content(cls, abspath, start=None, end=None):\n        \"\"\"Retrieve the content of the requested resource which is located\n        at the given absolute path.\n\n        This class method may be overridden by subclasses.  Note that its\n        signature is different from other overridable class methods\n        (no ``settings`` argument); this is deliberate to ensure that\n        ``abspath`` is able to stand on its own as a cache key.\n\n        This method should either return a byte string or an iterator\n        of byte strings.  The latter is preferred for large files\n        as it helps reduce memory fragmentation.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        with open(abspath, \"rb\") as file:\n            if start is not None:\n                file.seek(start)\n            if end is not None:\n                remaining = end - (start or 0)\n            else:\n                remaining = None\n            while True:\n                chunk_size = 64 * 1024\n                if remaining is not None and remaining < chunk_size:\n                    chunk_size = remaining\n                chunk = file.read(chunk_size)\n                if chunk:\n                    if remaining is not None:\n                        remaining -= len(chunk)\n                    yield chunk\n                else:\n                    if remaining is not None:\n                        assert remaining == 0\n                    return\n\n    @classmethod\n    def get_content_version(cls, abspath):\n        \"\"\"Returns a version string for the resource at the given path.\n\n        This class method may be overridden by subclasses.  The\n        default implementation is a hash of the file's contents.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        data = cls.get_content(abspath)\n        hasher = hashlib.md5()\n        if isinstance(data, bytes_type):\n            hasher.update(data)\n        else:\n            for chunk in data:\n                hasher.update(chunk)\n        return hasher.hexdigest()\n\n    def _stat(self):\n        if not hasattr(self, '_stat_result'):\n            self._stat_result = os.stat(self.absolute_path)\n        return self._stat_result\n\n    def get_content_size(self):\n        \"\"\"Retrieve the total size of the resource at the given path.\n\n        This method may be overridden by subclasses. It will only\n        be called if a partial result is requested from `get_content`\n\n        .. versionadded:: 3.1\n        \"\"\"\n        stat_result = self._stat()\n        return stat_result[stat.ST_SIZE]\n\n    def get_modified_time(self):\n        \"\"\"Returns the time that ``self.absolute_path`` was last modified.\n\n        May be overridden in subclasses.  Should return a `~datetime.datetime`\n        object or None.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        stat_result = self._stat()\n        modified = datetime.datetime.utcfromtimestamp(stat_result[stat.ST_MTIME])\n        return modified\n\n    def get_content_type(self):\n        \"\"\"Returns the ``Content-Type`` header to be used for this request.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        mime_type, encoding = mimetypes.guess_type(self.absolute_path)\n        return mime_type\n\n    def set_extra_headers(self, path):\n        \"\"\"For subclass to add extra headers to the response\"\"\"\n        pass\n\n    def get_cache_time(self, path, modified, mime_type):\n        \"\"\"Override to customize cache control behavior.\n\n        Return a positive number of seconds to make the result\n        cacheable for that amount of time or 0 to mark resource as\n        cacheable for an unspecified amount of time (subject to\n        browser heuristics).\n\n        By default returns cache expiry of 10 years for resources requested\n        with ``v`` argument.\n        \"\"\"\n        return self.CACHE_MAX_AGE if \"v\" in self.request.arguments else 0\n\n    @classmethod\n    def make_static_url(cls, settings, path, include_version=True):\n        \"\"\"Constructs a versioned url for the given path.\n\n        This method may be overridden in subclasses (but note that it\n        is a class method rather than an instance method).  Subclasses\n        are only required to implement the signature\n        ``make_static_url(cls, settings, path)``; other keyword\n        arguments may be passed through `~RequestHandler.static_url`\n        but are not standard.\n\n        ``settings`` is the `Application.settings` dictionary.  ``path``\n        is the static path being requested.  The url returned should be\n        relative to the current host.\n\n        ``include_version`` determines whether the generated URL should\n        include the query string containing the version hash of the\n        file corresponding to the given ``path``.\n\n        \"\"\"\n        url = settings.get('static_url_prefix', '/static/') + path\n        if not include_version:\n            return url\n\n        version_hash = cls.get_version(settings, path)\n        if not version_hash:\n            return url\n\n        return '%s?v=%s' % (url, version_hash)\n\n    def parse_url_path(self, url_path):\n        \"\"\"Converts a static URL path into a filesystem path.\n\n        ``url_path`` is the path component of the URL with\n        ``static_url_prefix`` removed.  The return value should be\n        filesystem path relative to ``static_path``.\n\n        This is the inverse of `make_static_url`.\n        \"\"\"\n        if os.path.sep != \"/\":\n            url_path = url_path.replace(\"/\", os.path.sep)\n        return url_path\n\n    @classmethod\n    def get_version(cls, settings, path):\n        \"\"\"Generate the version string to be used in static URLs.\n\n        ``settings`` is the `Application.settings` dictionary and ``path``\n        is the relative location of the requested asset on the filesystem.\n        The returned value should be a string, or ``None`` if no version\n        could be determined.\n\n        .. versionchanged:: 3.1\n           This method was previously recommended for subclasses to override;\n           `get_content_version` is now preferred as it allows the base\n           class to handle caching of the result.\n        \"\"\"\n        abs_path = cls.get_absolute_path(settings['static_path'], path)\n        return cls._get_cached_version(abs_path)\n\n    @classmethod\n    def _get_cached_version(cls, abs_path):\n        with cls._lock:\n            hashes = cls._static_hashes\n            if abs_path not in hashes:\n                try:\n                    hashes[abs_path] = cls.get_content_version(abs_path)\n                except Exception:\n                    gen_log.error(\"Could not open static file %r\", abs_path)\n                    hashes[abs_path] = None\n            hsh = hashes.get(abs_path)\n            if hsh:\n                return hsh\n        return None\n\n\nclass FallbackHandler(RequestHandler):\n    \"\"\"A `RequestHandler` that wraps another HTTP server callback.\n\n    The fallback is a callable object that accepts an\n    `~.httpserver.HTTPRequest`, such as an `Application` or\n    `tornado.wsgi.WSGIContainer`.  This is most useful to use both\n    Tornado ``RequestHandlers`` and WSGI in the same server.  Typical\n    usage::\n\n        wsgi_app = tornado.wsgi.WSGIContainer(\n            django.core.handlers.wsgi.WSGIHandler())\n        application = tornado.web.Application([\n            (r\"/foo\", FooHandler),\n            (r\".*\", FallbackHandler, dict(fallback=wsgi_app),\n        ])\n    \"\"\"\n    def initialize(self, fallback):\n        self.fallback = fallback\n\n    def prepare(self):\n        self.fallback(self.request)\n        self._finished = True\n\n\nclass OutputTransform(object):\n    \"\"\"A transform modifies the result of an HTTP request (e.g., GZip encoding)\n\n    A new transform instance is created for every request. See the\n    ChunkedTransferEncoding example below if you want to implement a\n    new Transform.\n    \"\"\"\n    def __init__(self, request):\n        pass\n\n    def transform_first_chunk(self, status_code, headers, chunk, finishing):\n        return status_code, headers, chunk\n\n    def transform_chunk(self, chunk, finishing):\n        return chunk\n\n\nclass GZipContentEncoding(OutputTransform):\n    \"\"\"Applies the gzip content encoding to the response.\n\n    See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11\n    \"\"\"\n    CONTENT_TYPES = set([\n        \"text/plain\", \"text/html\", \"text/css\", \"text/xml\", \"application/javascript\",\n        \"application/x-javascript\", \"application/xml\", \"application/atom+xml\",\n        \"text/javascript\", \"application/json\", \"application/xhtml+xml\"])\n    MIN_LENGTH = 5\n\n    def __init__(self, request):\n        self._gzipping = request.supports_http_1_1() and \\\n            \"gzip\" in request.headers.get(\"Accept-Encoding\", \"\")\n\n    def transform_first_chunk(self, status_code, headers, chunk, finishing):\n        if 'Vary' in headers:\n            headers['Vary'] += b', Accept-Encoding'\n        else:\n            headers['Vary'] = b'Accept-Encoding'\n        if self._gzipping:\n            ctype = _unicode(headers.get(\"Content-Type\", \"\")).split(\";\")[0]\n            self._gzipping = (ctype in self.CONTENT_TYPES) and \\\n                (not finishing or len(chunk) >= self.MIN_LENGTH) and \\\n                (finishing or \"Content-Length\" not in headers) and \\\n                (\"Content-Encoding\" not in headers)\n        if self._gzipping:\n            headers[\"Content-Encoding\"] = \"gzip\"\n            self._gzip_value = BytesIO()\n            self._gzip_file = gzip.GzipFile(mode=\"w\", fileobj=self._gzip_value)\n            chunk = self.transform_chunk(chunk, finishing)\n            if \"Content-Length\" in headers:\n                headers[\"Content-Length\"] = str(len(chunk))\n        return status_code, headers, chunk\n\n    def transform_chunk(self, chunk, finishing):\n        if self._gzipping:\n            self._gzip_file.write(chunk)\n            if finishing:\n                self._gzip_file.close()\n            else:\n                self._gzip_file.flush()\n            chunk = self._gzip_value.getvalue()\n            self._gzip_value.truncate(0)\n            self._gzip_value.seek(0)\n        return chunk\n\n\nclass ChunkedTransferEncoding(OutputTransform):\n    \"\"\"Applies the chunked transfer encoding to the response.\n\n    See http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.6.1\n    \"\"\"\n    def __init__(self, request):\n        self._chunking = request.supports_http_1_1()\n\n    def transform_first_chunk(self, status_code, headers, chunk, finishing):\n        # 304 responses have no body (not even a zero-length body), and so\n        # should not have either Content-Length or Transfer-Encoding headers.\n        if self._chunking and status_code != 304:\n            # No need to chunk the output if a Content-Length is specified\n            if \"Content-Length\" in headers or \"Transfer-Encoding\" in headers:\n                self._chunking = False\n            else:\n                headers[\"Transfer-Encoding\"] = \"chunked\"\n                chunk = self.transform_chunk(chunk, finishing)\n        return status_code, headers, chunk\n\n    def transform_chunk(self, block, finishing):\n        if self._chunking:\n            # Don't write out empty chunks because that means END-OF-STREAM\n            # with chunked encoding\n            if block:\n                block = utf8(\"%x\" % len(block)) + b\"\\r\\n\" + block + b\"\\r\\n\"\n            if finishing:\n                block += b\"0\\r\\n\\r\\n\"\n        return block\n\n\ndef authenticated(method):\n    \"\"\"Decorate methods with this to require that the user be logged in.\n\n    If the user is not logged in, they will be redirected to the configured\n    `login url <RequestHandler.get_login_url>`.\n    \"\"\"\n    @functools.wraps(method)\n    def wrapper(self, *args, **kwargs):\n        if not self.current_user:\n            if self.request.method in (\"GET\", \"HEAD\"):\n                url = self.get_login_url()\n                if \"?\" not in url:\n                    if urlparse.urlsplit(url).scheme:\n                        # if login url is absolute, make next absolute too\n                        next_url = self.request.full_url()\n                    else:\n                        next_url = self.request.uri\n                    url += \"?\" + urlencode(dict(next=next_url))\n                self.redirect(url)\n                return\n            raise HTTPError(403)\n        return method(self, *args, **kwargs)\n    return wrapper\n\n\nclass UIModule(object):\n    \"\"\"A re-usable, modular UI unit on a page.\n\n    UI modules often execute additional queries, and they can include\n    additional CSS and JavaScript that will be included in the output\n    page, which is automatically inserted on page render.\n    \"\"\"\n    def __init__(self, handler):\n        self.handler = handler\n        self.request = handler.request\n        self.ui = handler.ui\n        self.current_user = handler.current_user\n        self.locale = handler.locale\n\n    def render(self, *args, **kwargs):\n        \"\"\"Overridden in subclasses to return this module's output.\"\"\"\n        raise NotImplementedError()\n\n    def embedded_javascript(self):\n        \"\"\"Returns a JavaScript string that will be embedded in the page.\"\"\"\n        return None\n\n    def javascript_files(self):\n        \"\"\"Returns a list of JavaScript files required by this module.\"\"\"\n        return None\n\n    def embedded_css(self):\n        \"\"\"Returns a CSS string that will be embedded in the page.\"\"\"\n        return None\n\n    def css_files(self):\n        \"\"\"Returns a list of CSS files required by this module.\"\"\"\n        return None\n\n    def html_head(self):\n        \"\"\"Returns a CSS string that will be put in the <head/> element\"\"\"\n        return None\n\n    def html_body(self):\n        \"\"\"Returns an HTML string that will be put in the <body/> element\"\"\"\n        return None\n\n    def render_string(self, path, **kwargs):\n        \"\"\"Renders a template and returns it as a string.\"\"\"\n        return self.handler.render_string(path, **kwargs)\n\n\nclass _linkify(UIModule):\n    def render(self, text, **kwargs):\n        return escape.linkify(text, **kwargs)\n\n\nclass _xsrf_form_html(UIModule):\n    def render(self):\n        return self.handler.xsrf_form_html()\n\n\nclass TemplateModule(UIModule):\n    \"\"\"UIModule that simply renders the given template.\n\n    {% module Template(\"foo.html\") %} is similar to {% include \"foo.html\" %},\n    but the module version gets its own namespace (with kwargs passed to\n    Template()) instead of inheriting the outer template's namespace.\n\n    Templates rendered through this module also get access to UIModule's\n    automatic javascript/css features.  Simply call set_resources\n    inside the template and give it keyword arguments corresponding to\n    the methods on UIModule: {{ set_resources(js_files=static_url(\"my.js\")) }}\n    Note that these resources are output once per template file, not once\n    per instantiation of the template, so they must not depend on\n    any arguments to the template.\n    \"\"\"\n    def __init__(self, handler):\n        super(TemplateModule, self).__init__(handler)\n        # keep resources in both a list and a dict to preserve order\n        self._resource_list = []\n        self._resource_dict = {}\n\n    def render(self, path, **kwargs):\n        def set_resources(**kwargs):\n            if path not in self._resource_dict:\n                self._resource_list.append(kwargs)\n                self._resource_dict[path] = kwargs\n            else:\n                if self._resource_dict[path] != kwargs:\n                    raise ValueError(\"set_resources called with different \"\n                                     \"resources for the same template\")\n            return \"\"\n        return self.render_string(path, set_resources=set_resources,\n                                  **kwargs)\n\n    def _get_resources(self, key):\n        return (r[key] for r in self._resource_list if key in r)\n\n    def embedded_javascript(self):\n        return \"\\n\".join(self._get_resources(\"embedded_javascript\"))\n\n    def javascript_files(self):\n        result = []\n        for f in self._get_resources(\"javascript_files\"):\n            if isinstance(f, (unicode_type, bytes_type)):\n                result.append(f)\n            else:\n                result.extend(f)\n        return result\n\n    def embedded_css(self):\n        return \"\\n\".join(self._get_resources(\"embedded_css\"))\n\n    def css_files(self):\n        result = []\n        for f in self._get_resources(\"css_files\"):\n            if isinstance(f, (unicode_type, bytes_type)):\n                result.append(f)\n            else:\n                result.extend(f)\n        return result\n\n    def html_head(self):\n        return \"\".join(self._get_resources(\"html_head\"))\n\n    def html_body(self):\n        return \"\".join(self._get_resources(\"html_body\"))\n\n\nclass _UIModuleNamespace(object):\n    \"\"\"Lazy namespace which creates UIModule proxies bound to a handler.\"\"\"\n    def __init__(self, handler, ui_modules):\n        self.handler = handler\n        self.ui_modules = ui_modules\n\n    def __getitem__(self, key):\n        return self.handler._ui_module(key, self.ui_modules[key])\n\n    def __getattr__(self, key):\n        try:\n            return self[key]\n        except KeyError as e:\n            raise AttributeError(str(e))\n\n\nclass URLSpec(object):\n    \"\"\"Specifies mappings between URLs and handlers.\"\"\"\n    def __init__(self, pattern, handler_class, kwargs=None, name=None):\n        \"\"\"Parameters:\n\n        * ``pattern``: Regular expression to be matched.  Any groups\n          in the regex will be passed in to the handler's get/post/etc\n          methods as arguments.\n\n        * ``handler_class``: `RequestHandler` subclass to be invoked.\n\n        * ``kwargs`` (optional): A dictionary of additional arguments\n          to be passed to the handler's constructor.\n\n        * ``name`` (optional): A name for this handler.  Used by\n          `Application.reverse_url`.\n        \"\"\"\n        if not pattern.endswith('$'):\n            pattern += '$'\n        self.regex = re.compile(pattern)\n        assert len(self.regex.groupindex) in (0, self.regex.groups), \\\n            (\"groups in url regexes must either be all named or all \"\n             \"positional: %r\" % self.regex.pattern)\n        self.handler_class = handler_class\n        self.kwargs = kwargs or {}\n        self.name = name\n        self._path, self._group_count = self._find_groups()\n\n    def __repr__(self):\n        return '%s(%r, %s, kwargs=%r, name=%r)' % \\\n            (self.__class__.__name__, self.regex.pattern,\n             self.handler_class, self.kwargs, self.name)\n\n    def _find_groups(self):\n        \"\"\"Returns a tuple (reverse string, group count) for a url.\n\n        For example: Given the url pattern /([0-9]{4})/([a-z-]+)/, this method\n        would return ('/%s/%s/', 2).\n        \"\"\"\n        pattern = self.regex.pattern\n        if pattern.startswith('^'):\n            pattern = pattern[1:]\n        if pattern.endswith('$'):\n            pattern = pattern[:-1]\n\n        if self.regex.groups != pattern.count('('):\n            # The pattern is too complicated for our simplistic matching,\n            # so we can't support reversing it.\n            return (None, None)\n\n        pieces = []\n        for fragment in pattern.split('('):\n            if ')' in fragment:\n                paren_loc = fragment.index(')')\n                if paren_loc >= 0:\n                    pieces.append('%s' + fragment[paren_loc + 1:])\n            else:\n                pieces.append(fragment)\n\n        return (''.join(pieces), self.regex.groups)\n\n    def reverse(self, *args):\n        assert self._path is not None, \\\n            \"Cannot reverse url regex \" + self.regex.pattern\n        assert len(args) == self._group_count, \"required number of arguments \"\\\n            \"not found\"\n        if not len(args):\n            return self._path\n        converted_args = []\n        for a in args:\n            if not isinstance(a, (unicode_type, bytes_type)):\n                a = str(a)\n            converted_args.append(escape.url_escape(utf8(a), plus=False))\n        return self._path % tuple(converted_args)\n\nurl = URLSpec\n\n\nif hasattr(hmac, 'compare_digest'):  # python 3.3\n    _time_independent_equals = hmac.compare_digest\nelse:\n    def _time_independent_equals(a, b):\n        if len(a) != len(b):\n            return False\n        result = 0\n        if isinstance(a[0], int):  # python3 byte strings\n            for x, y in zip(a, b):\n                result |= x ^ y\n        else:  # python2\n            for x, y in zip(a, b):\n                result |= ord(x) ^ ord(y)\n        return result == 0\n\n\ndef create_signed_value(secret, name, value):\n    timestamp = utf8(str(int(time.time())))\n    value = base64.b64encode(utf8(value))\n    signature = _create_signature(secret, name, value, timestamp)\n    value = b\"|\".join([value, timestamp, signature])\n    return value\n\n\ndef decode_signed_value(secret, name, value, max_age_days=31):\n    if not value:\n        return None\n    parts = utf8(value).split(b\"|\")\n    if len(parts) != 3:\n        return None\n    signature = _create_signature(secret, name, parts[0], parts[1])\n    if not _time_independent_equals(parts[2], signature):\n        gen_log.warning(\"Invalid cookie signature %r\", value)\n        return None\n    timestamp = int(parts[1])\n    if timestamp < time.time() - max_age_days * 86400:\n        gen_log.warning(\"Expired cookie %r\", value)\n        return None\n    if timestamp > time.time() + 31 * 86400:\n        # _cookie_signature does not hash a delimiter between the\n        # parts of the cookie, so an attacker could transfer trailing\n        # digits from the payload to the timestamp without altering the\n        # signature.  For backwards compatibility, sanity-check timestamp\n        # here instead of modifying _cookie_signature.\n        gen_log.warning(\"Cookie timestamp in future; possible tampering %r\", value)\n        return None\n    if parts[1].startswith(b\"0\"):\n        gen_log.warning(\"Tampered cookie %r\", value)\n        return None\n    try:\n        return base64.b64decode(parts[0])\n    except Exception:\n        return None\n\n\ndef _create_signature(secret, *parts):\n    hash = hmac.new(utf8(secret), digestmod=hashlib.sha1)\n    for part in parts:\n        hash.update(utf8(part))\n    return utf8(hash.hexdigest())\n",
            "new_file_content": "#!/usr/bin/env python\n#\n# Copyright 2009 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"``tornado.web`` provides a simple web framework with asynchronous\nfeatures that allow it to scale to large numbers of open connections,\nmaking it ideal for `long polling\n<http://en.wikipedia.org/wiki/Push_technology#Long_polling>`_.\n\nHere is a simple \"Hello, world\" example app::\n\n    import tornado.ioloop\n    import tornado.web\n\n    class MainHandler(tornado.web.RequestHandler):\n        def get(self):\n            self.write(\"Hello, world\")\n\n    if __name__ == \"__main__\":\n        application = tornado.web.Application([\n            (r\"/\", MainHandler),\n        ])\n        application.listen(8888)\n        tornado.ioloop.IOLoop.instance().start()\n\nSee the :doc:`Tornado overview <overview>` for more details and a good getting\nstarted guide.\n\nThread-safety notes\n-------------------\n\nIn general, methods on `RequestHandler` and elsewhere in Tornado are\nnot thread-safe.  In particular, methods such as\n`~RequestHandler.write()`, `~RequestHandler.finish()`, and\n`~RequestHandler.flush()` must only be called from the main thread.  If\nyou use multiple threads it is important to use `.IOLoop.add_callback`\nto transfer control back to the main thread before finishing the\nrequest.\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function, with_statement\n\n\nimport base64\nimport binascii\nimport datetime\nimport email.utils\nimport functools\nimport gzip\nimport hashlib\nimport hmac\nimport mimetypes\nimport numbers\nimport os.path\nimport re\nimport stat\nimport sys\nimport threading\nimport time\nimport tornado\nimport traceback\nimport types\nimport uuid\n\nfrom tornado.concurrent import Future\nfrom tornado import escape\nfrom tornado import httputil\nfrom tornado import locale\nfrom tornado.log import access_log, app_log, gen_log\nfrom tornado import stack_context\nfrom tornado import template\nfrom tornado.escape import utf8, _unicode\nfrom tornado.util import bytes_type, import_object, ObjectDict, raise_exc_info, unicode_type\n\ntry:\n    from io import BytesIO  # python 3\nexcept ImportError:\n    from cStringIO import StringIO as BytesIO  # python 2\n\ntry:\n    import Cookie  # py2\nexcept ImportError:\n    import http.cookies as Cookie  # py3\n\ntry:\n    import urlparse  # py2\nexcept ImportError:\n    import urllib.parse as urlparse  # py3\n\ntry:\n    from urllib import urlencode  # py2\nexcept ImportError:\n    from urllib.parse import urlencode  # py3\n\n\nclass RequestHandler(object):\n    \"\"\"Subclass this class and define `get()` or `post()` to make a handler.\n\n    If you want to support more methods than the standard GET/HEAD/POST, you\n    should override the class variable ``SUPPORTED_METHODS`` in your\n    `RequestHandler` subclass.\n    \"\"\"\n    SUPPORTED_METHODS = (\"GET\", \"HEAD\", \"POST\", \"DELETE\", \"PATCH\", \"PUT\",\n                         \"OPTIONS\")\n\n    _template_loaders = {}  # {path: template.BaseLoader}\n    _template_loader_lock = threading.Lock()\n    _remove_control_chars_regex = re.compile(r\"[\\x00-\\x08\\x0e-\\x1f]\")\n\n    def __init__(self, application, request, **kwargs):\n        super(RequestHandler, self).__init__()\n\n        self.application = application\n        self.request = request\n        self._headers_written = False\n        self._finished = False\n        self._auto_finish = True\n        self._transforms = None  # will be set in _execute\n        self.path_args = None\n        self.path_kwargs = None\n        self.ui = ObjectDict((n, self._ui_method(m)) for n, m in\n                             application.ui_methods.items())\n        # UIModules are available as both `modules` and `_tt_modules` in the\n        # template namespace.  Historically only `modules` was available\n        # but could be clobbered by user additions to the namespace.\n        # The template {% module %} directive looks in `_tt_modules` to avoid\n        # possible conflicts.\n        self.ui[\"_tt_modules\"] = _UIModuleNamespace(self,\n                                                    application.ui_modules)\n        self.ui[\"modules\"] = self.ui[\"_tt_modules\"]\n        self.clear()\n        # Check since connection is not available in WSGI\n        if getattr(self.request, \"connection\", None):\n            self.request.connection.set_close_callback(\n                self.on_connection_close)\n        self.initialize(**kwargs)\n\n    def initialize(self):\n        \"\"\"Hook for subclass initialization.\n\n        A dictionary passed as the third argument of a url spec will be\n        supplied as keyword arguments to initialize().\n\n        Example::\n\n            class ProfileHandler(RequestHandler):\n                def initialize(self, database):\n                    self.database = database\n\n                def get(self, username):\n                    ...\n\n            app = Application([\n                (r'/user/(.*)', ProfileHandler, dict(database=database)),\n                ])\n        \"\"\"\n        pass\n\n    @property\n    def settings(self):\n        \"\"\"An alias for `self.application.settings <Application.settings>`.\"\"\"\n        return self.application.settings\n\n    def head(self, *args, **kwargs):\n        raise HTTPError(405)\n\n    def get(self, *args, **kwargs):\n        raise HTTPError(405)\n\n    def post(self, *args, **kwargs):\n        raise HTTPError(405)\n\n    def delete(self, *args, **kwargs):\n        raise HTTPError(405)\n\n    def patch(self, *args, **kwargs):\n        raise HTTPError(405)\n\n    def put(self, *args, **kwargs):\n        raise HTTPError(405)\n\n    def options(self, *args, **kwargs):\n        raise HTTPError(405)\n\n    def prepare(self):\n        \"\"\"Called at the beginning of a request before  `get`/`post`/etc.\n\n        Override this method to perform common initialization regardless\n        of the request method.\n\n        Asynchronous support: Decorate this method with `.gen.coroutine`\n        or `.return_future` to make it asynchronous (the\n        `asynchronous` decorator cannot be used on `prepare`).\n        If this method returns a `.Future` execution will not proceed\n        until the `.Future` is done.\n\n        .. versionadded:: 3.1\n           Asynchronous support.\n        \"\"\"\n        pass\n\n    def on_finish(self):\n        \"\"\"Called after the end of a request.\n\n        Override this method to perform cleanup, logging, etc.\n        This method is a counterpart to `prepare`.  ``on_finish`` may\n        not produce any output, as it is called after the response\n        has been sent to the client.\n        \"\"\"\n        pass\n\n    def on_connection_close(self):\n        \"\"\"Called in async handlers if the client closed the connection.\n\n        Override this to clean up resources associated with\n        long-lived connections.  Note that this method is called only if\n        the connection was closed during asynchronous processing; if you\n        need to do cleanup after every request override `on_finish`\n        instead.\n\n        Proxies may keep a connection open for a time (perhaps\n        indefinitely) after the client has gone away, so this method\n        may not be called promptly after the end user closes their\n        connection.\n        \"\"\"\n        pass\n\n    def clear(self):\n        \"\"\"Resets all headers and content for this response.\"\"\"\n        self._headers = httputil.HTTPHeaders({\n            \"Server\": \"TornadoServer/%s\" % tornado.version,\n            \"Content-Type\": \"text/html; charset=UTF-8\",\n            \"Date\": httputil.format_timestamp(time.time()),\n        })\n        self.set_default_headers()\n        if (not self.request.supports_http_1_1() and\n            getattr(self.request, 'connection', None) and\n                not self.request.connection.no_keep_alive):\n            conn_header = self.request.headers.get(\"Connection\")\n            if conn_header and (conn_header.lower() == \"keep-alive\"):\n                self.set_header(\"Connection\", \"Keep-Alive\")\n        self._write_buffer = []\n        self._status_code = 200\n        self._reason = httputil.responses[200]\n\n    def set_default_headers(self):\n        \"\"\"Override this to set HTTP headers at the beginning of the request.\n\n        For example, this is the place to set a custom ``Server`` header.\n        Note that setting such headers in the normal flow of request\n        processing may not do what you want, since headers may be reset\n        during error handling.\n        \"\"\"\n        pass\n\n    def set_status(self, status_code, reason=None):\n        \"\"\"Sets the status code for our response.\n\n        :arg int status_code: Response status code. If ``reason`` is ``None``,\n            it must be present in `httplib.responses <http.client.responses>`.\n        :arg string reason: Human-readable reason phrase describing the status\n            code. If ``None``, it will be filled in from\n            `httplib.responses <http.client.responses>`.\n        \"\"\"\n        self._status_code = status_code\n        if reason is not None:\n            self._reason = escape.native_str(reason)\n        else:\n            try:\n                self._reason = httputil.responses[status_code]\n            except KeyError:\n                raise ValueError(\"unknown status code %d\", status_code)\n\n    def get_status(self):\n        \"\"\"Returns the status code for our response.\"\"\"\n        return self._status_code\n\n    def set_header(self, name, value):\n        \"\"\"Sets the given response header name and value.\n\n        If a datetime is given, we automatically format it according to the\n        HTTP specification. If the value is not a string, we convert it to\n        a string. All header values are then encoded as UTF-8.\n        \"\"\"\n        self._headers[name] = self._convert_header_value(value)\n\n    def add_header(self, name, value):\n        \"\"\"Adds the given response header and value.\n\n        Unlike `set_header`, `add_header` may be called multiple times\n        to return multiple values for the same header.\n        \"\"\"\n        self._headers.add(name, self._convert_header_value(value))\n\n    def clear_header(self, name):\n        \"\"\"Clears an outgoing header, undoing a previous `set_header` call.\n\n        Note that this method does not apply to multi-valued headers\n        set by `add_header`.\n        \"\"\"\n        if name in self._headers:\n            del self._headers[name]\n\n    _INVALID_HEADER_CHAR_RE = re.compile(br\"[\\x00-\\x1f]\")\n\n    def _convert_header_value(self, value):\n        if isinstance(value, bytes_type):\n            pass\n        elif isinstance(value, unicode_type):\n            value = value.encode('utf-8')\n        elif isinstance(value, numbers.Integral):\n            # return immediately since we know the converted value will be safe\n            return str(value)\n        elif isinstance(value, datetime.datetime):\n            return httputil.format_timestamp(value)\n        else:\n            raise TypeError(\"Unsupported header value %r\" % value)\n        # If \\n is allowed into the header, it is possible to inject\n        # additional headers or split the request. Also cap length to\n        # prevent obviously erroneous values.\n        if (len(value) > 4000 or\n                RequestHandler._INVALID_HEADER_CHAR_RE.search(value)):\n            raise ValueError(\"Unsafe header value %r\", value)\n        return value\n\n    _ARG_DEFAULT = []\n\n    def get_argument(self, name, default=_ARG_DEFAULT, strip=True):\n        \"\"\"Returns the value of the argument with the given name.\n\n        If default is not provided, the argument is considered to be\n        required, and we raise a `MissingArgumentError` if it is missing.\n\n        If the argument appears in the url more than once, we return the\n        last value.\n\n        The returned value is always unicode.\n        \"\"\"\n        args = self.get_arguments(name, strip=strip)\n        if not args:\n            if default is self._ARG_DEFAULT:\n                raise MissingArgumentError(name)\n            return default\n        return args[-1]\n\n    def get_arguments(self, name, strip=True):\n        \"\"\"Returns a list of the arguments with the given name.\n\n        If the argument is not present, returns an empty list.\n\n        The returned values are always unicode.\n        \"\"\"\n\n        values = []\n        for v in self.request.arguments.get(name, []):\n            v = self.decode_argument(v, name=name)\n            if isinstance(v, unicode_type):\n                # Get rid of any weird control chars (unless decoding gave\n                # us bytes, in which case leave it alone)\n                v = RequestHandler._remove_control_chars_regex.sub(\" \", v)\n            if strip:\n                v = v.strip()\n            values.append(v)\n        return values\n\n    def decode_argument(self, value, name=None):\n        \"\"\"Decodes an argument from the request.\n\n        The argument has been percent-decoded and is now a byte string.\n        By default, this method decodes the argument as utf-8 and returns\n        a unicode string, but this may be overridden in subclasses.\n\n        This method is used as a filter for both `get_argument()` and for\n        values extracted from the url and passed to `get()`/`post()`/etc.\n\n        The name of the argument is provided if known, but may be None\n        (e.g. for unnamed groups in the url regex).\n        \"\"\"\n        return _unicode(value)\n\n    @property\n    def cookies(self):\n        \"\"\"An alias for `self.request.cookies <.httpserver.HTTPRequest.cookies>`.\"\"\"\n        return self.request.cookies\n\n    def get_cookie(self, name, default=None):\n        \"\"\"Gets the value of the cookie with the given name, else default.\"\"\"\n        if self.request.cookies is not None and name in self.request.cookies:\n            return self.request.cookies[name].value\n        return default\n\n    def set_cookie(self, name, value, domain=None, expires=None, path=\"/\",\n                   expires_days=None, **kwargs):\n        \"\"\"Sets the given cookie name/value with the given options.\n\n        Additional keyword arguments are set on the Cookie.Morsel\n        directly.\n        See http://docs.python.org/library/cookie.html#morsel-objects\n        for available attributes.\n        \"\"\"\n        # The cookie library only accepts type str, in both python 2 and 3\n        name = escape.native_str(name)\n        value = escape.native_str(value)\n        if re.search(r\"[\\x00-\\x20]\", name + value):\n            # Don't let us accidentally inject bad stuff\n            raise ValueError(\"Invalid cookie %r: %r\" % (name, value))\n        if not hasattr(self, \"_new_cookie\"):\n            self._new_cookie = Cookie.SimpleCookie()\n        if name in self._new_cookie:\n            del self._new_cookie[name]\n        self._new_cookie[name] = value\n        morsel = self._new_cookie[name]\n        if domain:\n            morsel[\"domain\"] = domain\n        if expires_days is not None and not expires:\n            expires = datetime.datetime.utcnow() + datetime.timedelta(\n                days=expires_days)\n        if expires:\n            morsel[\"expires\"] = httputil.format_timestamp(expires)\n        if path:\n            morsel[\"path\"] = path\n        for k, v in kwargs.items():\n            if k == 'max_age':\n                k = 'max-age'\n            morsel[k] = v\n\n    def clear_cookie(self, name, path=\"/\", domain=None):\n        \"\"\"Deletes the cookie with the given name.\"\"\"\n        expires = datetime.datetime.utcnow() - datetime.timedelta(days=365)\n        self.set_cookie(name, value=\"\", path=path, expires=expires,\n                        domain=domain)\n\n    def clear_all_cookies(self):\n        \"\"\"Deletes all the cookies the user sent with this request.\"\"\"\n        for name in self.request.cookies:\n            self.clear_cookie(name)\n\n    def set_secure_cookie(self, name, value, expires_days=30, **kwargs):\n        \"\"\"Signs and timestamps a cookie so it cannot be forged.\n\n        You must specify the ``cookie_secret`` setting in your Application\n        to use this method. It should be a long, random sequence of bytes\n        to be used as the HMAC secret for the signature.\n\n        To read a cookie set with this method, use `get_secure_cookie()`.\n\n        Note that the ``expires_days`` parameter sets the lifetime of the\n        cookie in the browser, but is independent of the ``max_age_days``\n        parameter to `get_secure_cookie`.\n\n        Secure cookies may contain arbitrary byte values, not just unicode\n        strings (unlike regular cookies)\n        \"\"\"\n        self.set_cookie(name, self.create_signed_value(name, value),\n                        expires_days=expires_days, **kwargs)\n\n    def create_signed_value(self, name, value):\n        \"\"\"Signs and timestamps a string so it cannot be forged.\n\n        Normally used via set_secure_cookie, but provided as a separate\n        method for non-cookie uses.  To decode a value not stored\n        as a cookie use the optional value argument to get_secure_cookie.\n        \"\"\"\n        self.require_setting(\"cookie_secret\", \"secure cookies\")\n        return create_signed_value(self.application.settings[\"cookie_secret\"],\n                                   name, value)\n\n    def get_secure_cookie(self, name, value=None, max_age_days=31):\n        \"\"\"Returns the given signed cookie if it validates, or None.\n\n        The decoded cookie value is returned as a byte string (unlike\n        `get_cookie`).\n        \"\"\"\n        self.require_setting(\"cookie_secret\", \"secure cookies\")\n        if value is None:\n            value = self.get_cookie(name)\n        return decode_signed_value(self.application.settings[\"cookie_secret\"],\n                                   name, value, max_age_days=max_age_days)\n\n    def redirect(self, url, permanent=False, status=None):\n        \"\"\"Sends a redirect to the given (optionally relative) URL.\n\n        If the ``status`` argument is specified, that value is used as the\n        HTTP status code; otherwise either 301 (permanent) or 302\n        (temporary) is chosen based on the ``permanent`` argument.\n        The default is 302 (temporary).\n        \"\"\"\n        if self._headers_written:\n            raise Exception(\"Cannot redirect after headers have been written\")\n        if status is None:\n            status = 301 if permanent else 302\n        else:\n            assert isinstance(status, int) and 300 <= status <= 399\n        self.set_status(status)\n        self.set_header(\"Location\", urlparse.urljoin(utf8(self.request.uri),\n                                                     utf8(url)))\n        self.finish()\n\n    def write(self, chunk):\n        \"\"\"Writes the given chunk to the output buffer.\n\n        To write the output to the network, use the flush() method below.\n\n        If the given chunk is a dictionary, we write it as JSON and set\n        the Content-Type of the response to be ``application/json``.\n        (if you want to send JSON as a different ``Content-Type``, call\n        set_header *after* calling write()).\n\n        Note that lists are not converted to JSON because of a potential\n        cross-site security vulnerability.  All JSON output should be\n        wrapped in a dictionary.  More details at\n        http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx\n        \"\"\"\n        if self._finished:\n            raise RuntimeError(\"Cannot write() after finish().  May be caused \"\n                               \"by using async operations without the \"\n                               \"@asynchronous decorator.\")\n        if isinstance(chunk, dict):\n            chunk = escape.json_encode(chunk)\n            self.set_header(\"Content-Type\", \"application/json; charset=UTF-8\")\n        chunk = utf8(chunk)\n        self._write_buffer.append(chunk)\n\n    def render(self, template_name, **kwargs):\n        \"\"\"Renders the template with the given arguments as the response.\"\"\"\n        html = self.render_string(template_name, **kwargs)\n\n        # Insert the additional JS and CSS added by the modules on the page\n        js_embed = []\n        js_files = []\n        css_embed = []\n        css_files = []\n        html_heads = []\n        html_bodies = []\n        for module in getattr(self, \"_active_modules\", {}).values():\n            embed_part = module.embedded_javascript()\n            if embed_part:\n                js_embed.append(utf8(embed_part))\n            file_part = module.javascript_files()\n            if file_part:\n                if isinstance(file_part, (unicode_type, bytes_type)):\n                    js_files.append(file_part)\n                else:\n                    js_files.extend(file_part)\n            embed_part = module.embedded_css()\n            if embed_part:\n                css_embed.append(utf8(embed_part))\n            file_part = module.css_files()\n            if file_part:\n                if isinstance(file_part, (unicode_type, bytes_type)):\n                    css_files.append(file_part)\n                else:\n                    css_files.extend(file_part)\n            head_part = module.html_head()\n            if head_part:\n                html_heads.append(utf8(head_part))\n            body_part = module.html_body()\n            if body_part:\n                html_bodies.append(utf8(body_part))\n\n        def is_absolute(path):\n            return any(path.startswith(x) for x in [\"/\", \"http:\", \"https:\"])\n        if js_files:\n            # Maintain order of JavaScript files given by modules\n            paths = []\n            unique_paths = set()\n            for path in js_files:\n                if not is_absolute(path):\n                    path = self.static_url(path)\n                if path not in unique_paths:\n                    paths.append(path)\n                    unique_paths.add(path)\n            js = ''.join('<script src=\"' + escape.xhtml_escape(p) +\n                         '\" type=\"text/javascript\"></script>'\n                         for p in paths)\n            sloc = html.rindex(b'</body>')\n            html = html[:sloc] + utf8(js) + b'\\n' + html[sloc:]\n        if js_embed:\n            js = b'<script type=\"text/javascript\">\\n//<![CDATA[\\n' + \\\n                b'\\n'.join(js_embed) + b'\\n//]]>\\n</script>'\n            sloc = html.rindex(b'</body>')\n            html = html[:sloc] + js + b'\\n' + html[sloc:]\n        if css_files:\n            paths = []\n            unique_paths = set()\n            for path in css_files:\n                if not is_absolute(path):\n                    path = self.static_url(path)\n                if path not in unique_paths:\n                    paths.append(path)\n                    unique_paths.add(path)\n            css = ''.join('<link href=\"' + escape.xhtml_escape(p) + '\" '\n                          'type=\"text/css\" rel=\"stylesheet\"/>'\n                          for p in paths)\n            hloc = html.index(b'</head>')\n            html = html[:hloc] + utf8(css) + b'\\n' + html[hloc:]\n        if css_embed:\n            css = b'<style type=\"text/css\">\\n' + b'\\n'.join(css_embed) + \\\n                b'\\n</style>'\n            hloc = html.index(b'</head>')\n            html = html[:hloc] + css + b'\\n' + html[hloc:]\n        if html_heads:\n            hloc = html.index(b'</head>')\n            html = html[:hloc] + b''.join(html_heads) + b'\\n' + html[hloc:]\n        if html_bodies:\n            hloc = html.index(b'</body>')\n            html = html[:hloc] + b''.join(html_bodies) + b'\\n' + html[hloc:]\n        self.finish(html)\n\n    def render_string(self, template_name, **kwargs):\n        \"\"\"Generate the given template with the given arguments.\n\n        We return the generated byte string (in utf8). To generate and\n        write a template as a response, use render() above.\n        \"\"\"\n        # If no template_path is specified, use the path of the calling file\n        template_path = self.get_template_path()\n        if not template_path:\n            frame = sys._getframe(0)\n            web_file = frame.f_code.co_filename\n            while frame.f_code.co_filename == web_file:\n                frame = frame.f_back\n            template_path = os.path.dirname(frame.f_code.co_filename)\n        with RequestHandler._template_loader_lock:\n            if template_path not in RequestHandler._template_loaders:\n                loader = self.create_template_loader(template_path)\n                RequestHandler._template_loaders[template_path] = loader\n            else:\n                loader = RequestHandler._template_loaders[template_path]\n        t = loader.load(template_name)\n        namespace = self.get_template_namespace()\n        namespace.update(kwargs)\n        return t.generate(**namespace)\n\n    def get_template_namespace(self):\n        \"\"\"Returns a dictionary to be used as the default template namespace.\n\n        May be overridden by subclasses to add or modify values.\n\n        The results of this method will be combined with additional\n        defaults in the `tornado.template` module and keyword arguments\n        to `render` or `render_string`.\n        \"\"\"\n        namespace = dict(\n            handler=self,\n            request=self.request,\n            current_user=self.current_user,\n            locale=self.locale,\n            _=self.locale.translate,\n            static_url=self.static_url,\n            xsrf_form_html=self.xsrf_form_html,\n            reverse_url=self.reverse_url\n        )\n        namespace.update(self.ui)\n        return namespace\n\n    def create_template_loader(self, template_path):\n        \"\"\"Returns a new template loader for the given path.\n\n        May be overridden by subclasses.  By default returns a\n        directory-based loader on the given path, using the\n        ``autoescape`` application setting.  If a ``template_loader``\n        application setting is supplied, uses that instead.\n        \"\"\"\n        settings = self.application.settings\n        if \"template_loader\" in settings:\n            return settings[\"template_loader\"]\n        kwargs = {}\n        if \"autoescape\" in settings:\n            # autoescape=None means \"no escaping\", so we have to be sure\n            # to only pass this kwarg if the user asked for it.\n            kwargs[\"autoescape\"] = settings[\"autoescape\"]\n        return template.Loader(template_path, **kwargs)\n\n    def flush(self, include_footers=False, callback=None):\n        \"\"\"Flushes the current output buffer to the network.\n\n        The ``callback`` argument, if given, can be used for flow control:\n        it will be run when all flushed data has been written to the socket.\n        Note that only one flush callback can be outstanding at a time;\n        if another flush occurs before the previous flush's callback\n        has been run, the previous callback will be discarded.\n        \"\"\"\n        if self.application._wsgi:\n            # WSGI applications cannot usefully support flush, so just make\n            # it a no-op (and run the callback immediately).\n            if callback is not None:\n                callback()\n            return\n\n        chunk = b\"\".join(self._write_buffer)\n        self._write_buffer = []\n        if not self._headers_written:\n            self._headers_written = True\n            for transform in self._transforms:\n                self._status_code, self._headers, chunk = \\\n                    transform.transform_first_chunk(\n                        self._status_code, self._headers, chunk, include_footers)\n            headers = self._generate_headers()\n        else:\n            for transform in self._transforms:\n                chunk = transform.transform_chunk(chunk, include_footers)\n            headers = b\"\"\n\n        # Ignore the chunk and only write the headers for HEAD requests\n        if self.request.method == \"HEAD\":\n            if headers:\n                self.request.write(headers, callback=callback)\n            return\n\n        self.request.write(headers + chunk, callback=callback)\n\n    def finish(self, chunk=None):\n        \"\"\"Finishes this response, ending the HTTP request.\"\"\"\n        if self._finished:\n            raise RuntimeError(\"finish() called twice.  May be caused \"\n                               \"by using async operations without the \"\n                               \"@asynchronous decorator.\")\n\n        if chunk is not None:\n            self.write(chunk)\n\n        # Automatically support ETags and add the Content-Length header if\n        # we have not flushed any content yet.\n        if not self._headers_written:\n            if (self._status_code == 200 and\n                self.request.method in (\"GET\", \"HEAD\") and\n                    \"Etag\" not in self._headers):\n                self.set_etag_header()\n                if self.check_etag_header():\n                    self._write_buffer = []\n                    self.set_status(304)\n            if self._status_code == 304:\n                assert not self._write_buffer, \"Cannot send body with 304\"\n                self._clear_headers_for_304()\n            elif \"Content-Length\" not in self._headers:\n                content_length = sum(len(part) for part in self._write_buffer)\n                self.set_header(\"Content-Length\", content_length)\n\n        if hasattr(self.request, \"connection\"):\n            # Now that the request is finished, clear the callback we\n            # set on the IOStream (which would otherwise prevent the\n            # garbage collection of the RequestHandler when there\n            # are keepalive connections)\n            self.request.connection.stream.set_close_callback(None)\n\n        if not self.application._wsgi:\n            self.flush(include_footers=True)\n            self.request.finish()\n            self._log()\n        self._finished = True\n        self.on_finish()\n        # Break up a reference cycle between this handler and the\n        # _ui_module closures to allow for faster GC on CPython.\n        self.ui = None\n\n    def send_error(self, status_code=500, **kwargs):\n        \"\"\"Sends the given HTTP error code to the browser.\n\n        If `flush()` has already been called, it is not possible to send\n        an error, so this method will simply terminate the response.\n        If output has been written but not yet flushed, it will be discarded\n        and replaced with the error page.\n\n        Override `write_error()` to customize the error page that is returned.\n        Additional keyword arguments are passed through to `write_error`.\n        \"\"\"\n        if self._headers_written:\n            gen_log.error(\"Cannot send error response after headers written\")\n            if not self._finished:\n                self.finish()\n            return\n        self.clear()\n\n        reason = None\n        if 'exc_info' in kwargs:\n            exception = kwargs['exc_info'][1]\n            if isinstance(exception, HTTPError) and exception.reason:\n                reason = exception.reason\n        self.set_status(status_code, reason=reason)\n        try:\n            self.write_error(status_code, **kwargs)\n        except Exception:\n            app_log.error(\"Uncaught exception in write_error\", exc_info=True)\n        if not self._finished:\n            self.finish()\n\n    def write_error(self, status_code, **kwargs):\n        \"\"\"Override to implement custom error pages.\n\n        ``write_error`` may call `write`, `render`, `set_header`, etc\n        to produce output as usual.\n\n        If this error was caused by an uncaught exception (including\n        HTTPError), an ``exc_info`` triple will be available as\n        ``kwargs[\"exc_info\"]``.  Note that this exception may not be\n        the \"current\" exception for purposes of methods like\n        ``sys.exc_info()`` or ``traceback.format_exc``.\n\n        For historical reasons, if a method ``get_error_html`` exists,\n        it will be used instead of the default ``write_error`` implementation.\n        ``get_error_html`` returned a string instead of producing output\n        normally, and had different semantics for exception handling.\n        Users of ``get_error_html`` are encouraged to convert their code\n        to override ``write_error`` instead.\n        \"\"\"\n        if hasattr(self, 'get_error_html'):\n            if 'exc_info' in kwargs:\n                exc_info = kwargs.pop('exc_info')\n                kwargs['exception'] = exc_info[1]\n                try:\n                    # Put the traceback into sys.exc_info()\n                    raise_exc_info(exc_info)\n                except Exception:\n                    self.finish(self.get_error_html(status_code, **kwargs))\n            else:\n                self.finish(self.get_error_html(status_code, **kwargs))\n            return\n        if self.settings.get(\"debug\") and \"exc_info\" in kwargs:\n            # in debug mode, try to send a traceback\n            self.set_header('Content-Type', 'text/plain')\n            for line in traceback.format_exception(*kwargs[\"exc_info\"]):\n                self.write(line)\n            self.finish()\n        else:\n            self.finish(\"<html><title>%(code)d: %(message)s</title>\"\n                        \"<body>%(code)d: %(message)s</body></html>\" % {\n                            \"code\": status_code,\n                            \"message\": self._reason,\n                        })\n\n    @property\n    def locale(self):\n        \"\"\"The local for the current session.\n\n        Determined by either `get_user_locale`, which you can override to\n        set the locale based on, e.g., a user preference stored in a\n        database, or `get_browser_locale`, which uses the ``Accept-Language``\n        header.\n        \"\"\"\n        if not hasattr(self, \"_locale\"):\n            self._locale = self.get_user_locale()\n            if not self._locale:\n                self._locale = self.get_browser_locale()\n                assert self._locale\n        return self._locale\n\n    def get_user_locale(self):\n        \"\"\"Override to determine the locale from the authenticated user.\n\n        If None is returned, we fall back to `get_browser_locale()`.\n\n        This method should return a `tornado.locale.Locale` object,\n        most likely obtained via a call like ``tornado.locale.get(\"en\")``\n        \"\"\"\n        return None\n\n    def get_browser_locale(self, default=\"en_US\"):\n        \"\"\"Determines the user's locale from ``Accept-Language`` header.\n\n        See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4\n        \"\"\"\n        if \"Accept-Language\" in self.request.headers:\n            languages = self.request.headers[\"Accept-Language\"].split(\",\")\n            locales = []\n            for language in languages:\n                parts = language.strip().split(\";\")\n                if len(parts) > 1 and parts[1].startswith(\"q=\"):\n                    try:\n                        score = float(parts[1][2:])\n                    except (ValueError, TypeError):\n                        score = 0.0\n                else:\n                    score = 1.0\n                locales.append((parts[0], score))\n            if locales:\n                locales.sort(key=lambda pair: pair[1], reverse=True)\n                codes = [l[0] for l in locales]\n                return locale.get(*codes)\n        return locale.get(default)\n\n    @property\n    def current_user(self):\n        \"\"\"The authenticated user for this request.\n\n        This is a cached version of `get_current_user`, which you can\n        override to set the user based on, e.g., a cookie. If that\n        method is not overridden, this method always returns None.\n\n        We lazy-load the current user the first time this method is called\n        and cache the result after that.\n        \"\"\"\n        if not hasattr(self, \"_current_user\"):\n            self._current_user = self.get_current_user()\n        return self._current_user\n\n    @current_user.setter\n    def current_user(self, value):\n        self._current_user = value\n\n    def get_current_user(self):\n        \"\"\"Override to determine the current user from, e.g., a cookie.\"\"\"\n        return None\n\n    def get_login_url(self):\n        \"\"\"Override to customize the login URL based on the request.\n\n        By default, we use the ``login_url`` application setting.\n        \"\"\"\n        self.require_setting(\"login_url\", \"@tornado.web.authenticated\")\n        return self.application.settings[\"login_url\"]\n\n    def get_template_path(self):\n        \"\"\"Override to customize template path for each handler.\n\n        By default, we use the ``template_path`` application setting.\n        Return None to load templates relative to the calling file.\n        \"\"\"\n        return self.application.settings.get(\"template_path\")\n\n    @property\n    def xsrf_token(self):\n        \"\"\"The XSRF-prevention token for the current user/session.\n\n        To prevent cross-site request forgery, we set an '_xsrf' cookie\n        and include the same '_xsrf' value as an argument with all POST\n        requests. If the two do not match, we reject the form submission\n        as a potential forgery.\n\n        See http://en.wikipedia.org/wiki/Cross-site_request_forgery\n        \"\"\"\n        if not hasattr(self, \"_xsrf_token\"):\n            token = self.get_cookie(\"_xsrf\")\n            if not token:\n                token = binascii.b2a_hex(uuid.uuid4().bytes)\n                expires_days = 30 if self.current_user else None\n                self.set_cookie(\"_xsrf\", token, expires_days=expires_days)\n            self._xsrf_token = token\n        return self._xsrf_token\n\n    def check_xsrf_cookie(self):\n        \"\"\"Verifies that the ``_xsrf`` cookie matches the ``_xsrf`` argument.\n\n        To prevent cross-site request forgery, we set an ``_xsrf``\n        cookie and include the same value as a non-cookie\n        field with all ``POST`` requests. If the two do not match, we\n        reject the form submission as a potential forgery.\n\n        The ``_xsrf`` value may be set as either a form field named ``_xsrf``\n        or in a custom HTTP header named ``X-XSRFToken`` or ``X-CSRFToken``\n        (the latter is accepted for compatibility with Django).\n\n        See http://en.wikipedia.org/wiki/Cross-site_request_forgery\n\n        Prior to release 1.1.1, this check was ignored if the HTTP header\n        ``X-Requested-With: XMLHTTPRequest`` was present.  This exception\n        has been shown to be insecure and has been removed.  For more\n        information please see\n        http://www.djangoproject.com/weblog/2011/feb/08/security/\n        http://weblog.rubyonrails.org/2011/2/8/csrf-protection-bypass-in-ruby-on-rails\n        \"\"\"\n        token = (self.get_argument(\"_xsrf\", None) or\n                 self.request.headers.get(\"X-Xsrftoken\") or\n                 self.request.headers.get(\"X-Csrftoken\"))\n        if not token:\n            raise HTTPError(403, \"'_xsrf' argument missing from POST\")\n        if self.xsrf_token != token:\n            raise HTTPError(403, \"XSRF cookie does not match POST argument\")\n\n    def xsrf_form_html(self):\n        \"\"\"An HTML ``<input/>`` element to be included with all POST forms.\n\n        It defines the ``_xsrf`` input value, which we check on all POST\n        requests to prevent cross-site request forgery. If you have set\n        the ``xsrf_cookies`` application setting, you must include this\n        HTML within all of your HTML forms.\n\n        In a template, this method should be called with ``{% module\n        xsrf_form_html() %}``\n\n        See `check_xsrf_cookie()` above for more information.\n        \"\"\"\n        return '<input type=\"hidden\" name=\"_xsrf\" value=\"' + \\\n            escape.xhtml_escape(self.xsrf_token) + '\"/>'\n\n    def static_url(self, path, include_host=None, **kwargs):\n        \"\"\"Returns a static URL for the given relative static file path.\n\n        This method requires you set the ``static_path`` setting in your\n        application (which specifies the root directory of your static\n        files).\n\n        This method returns a versioned url (by default appending\n        ``?v=<signature>``), which allows the static files to be\n        cached indefinitely.  This can be disabled by passing\n        ``include_version=False`` (in the default implementation;\n        other static file implementations are not required to support\n        this, but they may support other options).\n\n        By default this method returns URLs relative to the current\n        host, but if ``include_host`` is true the URL returned will be\n        absolute.  If this handler has an ``include_host`` attribute,\n        that value will be used as the default for all `static_url`\n        calls that do not pass ``include_host`` as a keyword argument.\n\n        \"\"\"\n        self.require_setting(\"static_path\", \"static_url\")\n        get_url = self.settings.get(\"static_handler_class\",\n                                    StaticFileHandler).make_static_url\n\n        if include_host is None:\n            include_host = getattr(self, \"include_host\", False)\n\n        if include_host:\n            base = self.request.protocol + \"://\" + self.request.host\n        else:\n            base = \"\"\n\n        return base + get_url(self.settings, path, **kwargs)\n\n    def async_callback(self, callback, *args, **kwargs):\n        \"\"\"Obsolete - catches exceptions from the wrapped function.\n\n        This function is unnecessary since Tornado 1.1.\n        \"\"\"\n        if callback is None:\n            return None\n        if args or kwargs:\n            callback = functools.partial(callback, *args, **kwargs)\n\n        def wrapper(*args, **kwargs):\n            try:\n                return callback(*args, **kwargs)\n            except Exception as e:\n                if self._headers_written:\n                    app_log.error(\"Exception after headers written\",\n                                  exc_info=True)\n                else:\n                    self._handle_request_exception(e)\n        return wrapper\n\n    def require_setting(self, name, feature=\"this feature\"):\n        \"\"\"Raises an exception if the given app setting is not defined.\"\"\"\n        if not self.application.settings.get(name):\n            raise Exception(\"You must define the '%s' setting in your \"\n                            \"application to use %s\" % (name, feature))\n\n    def reverse_url(self, name, *args):\n        \"\"\"Alias for `Application.reverse_url`.\"\"\"\n        return self.application.reverse_url(name, *args)\n\n    def compute_etag(self):\n        \"\"\"Computes the etag header to be used for this request.\n\n        By default uses a hash of the content written so far.\n\n        May be overridden to provide custom etag implementations,\n        or may return None to disable tornado's default etag support.\n        \"\"\"\n        hasher = hashlib.sha1()\n        for part in self._write_buffer:\n            hasher.update(part)\n        return '\"%s\"' % hasher.hexdigest()\n\n    def set_etag_header(self):\n        \"\"\"Sets the response's Etag header using ``self.compute_etag()``.\n\n        Note: no header will be set if ``compute_etag()`` returns ``None``.\n\n        This method is called automatically when the request is finished.\n        \"\"\"\n        etag = self.compute_etag()\n        if etag is not None:\n            self.set_header(\"Etag\", etag)\n\n    def check_etag_header(self):\n        \"\"\"Checks the ``Etag`` header against requests's ``If-None-Match``.\n\n        Returns ``True`` if the request's Etag matches and a 304 should be\n        returned. For example::\n\n            self.set_etag_header()\n            if self.check_etag_header():\n                self.set_status(304)\n                return\n\n        This method is called automatically when the request is finished,\n        but may be called earlier for applications that override\n        `compute_etag` and want to do an early check for ``If-None-Match``\n        before completing the request.  The ``Etag`` header should be set\n        (perhaps with `set_etag_header`) before calling this method.\n        \"\"\"\n        etag = self._headers.get(\"Etag\")\n        inm = utf8(self.request.headers.get(\"If-None-Match\", \"\"))\n        return bool(etag and inm and inm.find(etag) >= 0)\n\n    def _stack_context_handle_exception(self, type, value, traceback):\n        try:\n            # For historical reasons _handle_request_exception only takes\n            # the exception value instead of the full triple,\n            # so re-raise the exception to ensure that it's in\n            # sys.exc_info()\n            raise_exc_info((type, value, traceback))\n        except Exception:\n            self._handle_request_exception(value)\n        return True\n\n    def _execute(self, transforms, *args, **kwargs):\n        \"\"\"Executes this request with the given output transforms.\"\"\"\n        self._transforms = transforms\n        try:\n            if self.request.method not in self.SUPPORTED_METHODS:\n                raise HTTPError(405)\n            self.path_args = [self.decode_argument(arg) for arg in args]\n            self.path_kwargs = dict((k, self.decode_argument(v, name=k))\n                                    for (k, v) in kwargs.items())\n            # If XSRF cookies are turned on, reject form submissions without\n            # the proper cookie\n            if self.request.method not in (\"GET\", \"HEAD\", \"OPTIONS\") and \\\n                    self.application.settings.get(\"xsrf_cookies\"):\n                self.check_xsrf_cookie()\n            self._when_complete(self.prepare(), self._execute_method)\n        except Exception as e:\n            self._handle_request_exception(e)\n\n    def _when_complete(self, result, callback):\n        try:\n            if result is None:\n                callback()\n            elif isinstance(result, Future):\n                if result.done():\n                    if result.result() is not None:\n                        raise ValueError('Expected None, got %r' % result.result())\n                    callback()\n                else:\n                    # Delayed import of IOLoop because it's not available\n                    # on app engine\n                    from tornado.ioloop import IOLoop\n                    IOLoop.current().add_future(\n                        result, functools.partial(self._when_complete,\n                                                  callback=callback))\n            else:\n                raise ValueError(\"Expected Future or None, got %r\" % result)\n        except Exception as e:\n            self._handle_request_exception(e)\n\n    def _execute_method(self):\n        if not self._finished:\n            method = getattr(self, self.request.method.lower())\n            self._when_complete(method(*self.path_args, **self.path_kwargs),\n                                self._execute_finish)\n\n    def _execute_finish(self):\n        if self._auto_finish and not self._finished:\n            self.finish()\n\n    def _generate_headers(self):\n        reason = self._reason\n        lines = [utf8(self.request.version + \" \" +\n                      str(self._status_code) +\n                      \" \" + reason)]\n        lines.extend([utf8(n) + b\": \" + utf8(v) for n, v in self._headers.get_all()])\n\n        if hasattr(self, \"_new_cookie\"):\n            for cookie in self._new_cookie.values():\n                lines.append(utf8(\"Set-Cookie: \" + cookie.OutputString(None)))\n        return b\"\\r\\n\".join(lines) + b\"\\r\\n\\r\\n\"\n\n    def _log(self):\n        \"\"\"Logs the current request.\n\n        Sort of deprecated since this functionality was moved to the\n        Application, but left in place for the benefit of existing apps\n        that have overridden this method.\n        \"\"\"\n        self.application.log_request(self)\n\n    def _request_summary(self):\n        return self.request.method + \" \" + self.request.uri + \\\n            \" (\" + self.request.remote_ip + \")\"\n\n    def _handle_request_exception(self, e):\n        self.log_exception(*sys.exc_info())\n        if self._finished:\n            # Extra errors after the request has been finished should\n            # be logged, but there is no reason to continue to try and\n            # send a response.\n            return\n        if isinstance(e, HTTPError):\n            if e.status_code not in httputil.responses and not e.reason:\n                gen_log.error(\"Bad HTTP status code: %d\", e.status_code)\n                self.send_error(500, exc_info=sys.exc_info())\n            else:\n                self.send_error(e.status_code, exc_info=sys.exc_info())\n        else:\n            self.send_error(500, exc_info=sys.exc_info())\n\n    def log_exception(self, typ, value, tb):\n        \"\"\"Override to customize logging of uncaught exceptions.\n\n        By default logs instances of `HTTPError` as warnings without\n        stack traces (on the ``tornado.general`` logger), and all\n        other exceptions as errors with stack traces (on the\n        ``tornado.application`` logger).\n\n        .. versionadded:: 3.1\n        \"\"\"\n        if isinstance(value, HTTPError):\n            if value.log_message:\n                format = \"%d %s: \" + value.log_message\n                args = ([value.status_code, self._request_summary()] +\n                        list(value.args))\n                gen_log.warning(format, *args)\n        else:\n            app_log.error(\"Uncaught exception %s\\n%r\", self._request_summary(),\n                          self.request, exc_info=(typ, value, tb))\n\n    def _ui_module(self, name, module):\n        def render(*args, **kwargs):\n            if not hasattr(self, \"_active_modules\"):\n                self._active_modules = {}\n            if name not in self._active_modules:\n                self._active_modules[name] = module(self)\n            rendered = self._active_modules[name].render(*args, **kwargs)\n            return rendered\n        return render\n\n    def _ui_method(self, method):\n        return lambda *args, **kwargs: method(self, *args, **kwargs)\n\n    def _clear_headers_for_304(self):\n        # 304 responses should not contain entity headers (defined in\n        # http://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html#sec7.1)\n        # not explicitly allowed by\n        # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5\n        headers = [\"Allow\", \"Content-Encoding\", \"Content-Language\",\n                   \"Content-Length\", \"Content-MD5\", \"Content-Range\",\n                   \"Content-Type\", \"Last-Modified\"]\n        for h in headers:\n            self.clear_header(h)\n\n\ndef asynchronous(method):\n    \"\"\"Wrap request handler methods with this if they are asynchronous.\n\n    This decorator is unnecessary if the method is also decorated with\n    ``@gen.coroutine`` (it is legal but unnecessary to use the two\n    decorators together, in which case ``@asynchronous`` must be\n    first).\n\n    This decorator should only be applied to the :ref:`HTTP verb\n    methods <verbs>`; its behavior is undefined for any other method.\n    This decorator does not *make* a method asynchronous; it tells\n    the framework that the method *is* asynchronous.  For this decorator\n    to be useful the method must (at least sometimes) do something\n    asynchronous.\n\n    If this decorator is given, the response is not finished when the\n    method returns. It is up to the request handler to call\n    `self.finish() <RequestHandler.finish>` to finish the HTTP\n    request. Without this decorator, the request is automatically\n    finished when the ``get()`` or ``post()`` method returns. Example::\n\n       class MyRequestHandler(web.RequestHandler):\n           @web.asynchronous\n           def get(self):\n              http = httpclient.AsyncHTTPClient()\n              http.fetch(\"http://friendfeed.com/\", self._on_download)\n\n           def _on_download(self, response):\n              self.write(\"Downloaded!\")\n              self.finish()\n\n    .. versionadded:: 3.1\n       The ability to use ``@gen.coroutine`` without ``@asynchronous``.\n    \"\"\"\n    # Delay the IOLoop import because it's not available on app engine.\n    from tornado.ioloop import IOLoop\n    @functools.wraps(method)\n    def wrapper(self, *args, **kwargs):\n        if self.application._wsgi:\n            raise Exception(\"@asynchronous is not supported for WSGI apps\")\n        self._auto_finish = False\n        with stack_context.ExceptionStackContext(\n                self._stack_context_handle_exception):\n            result = method(self, *args, **kwargs)\n            if isinstance(result, Future):\n                # If @asynchronous is used with @gen.coroutine, (but\n                # not @gen.engine), we can automatically finish the\n                # request when the future resolves.  Additionally,\n                # the Future will swallow any exceptions so we need\n                # to throw them back out to the stack context to finish\n                # the request.\n                def future_complete(f):\n                    f.result()\n                    if not self._finished:\n                        self.finish()\n                IOLoop.current().add_future(result, future_complete)\n            return result\n    return wrapper\n\n\ndef removeslash(method):\n    \"\"\"Use this decorator to remove trailing slashes from the request path.\n\n    For example, a request to ``/foo/`` would redirect to ``/foo`` with this\n    decorator. Your request handler mapping should use a regular expression\n    like ``r'/foo/*'`` in conjunction with using the decorator.\n    \"\"\"\n    @functools.wraps(method)\n    def wrapper(self, *args, **kwargs):\n        if self.request.path.endswith(\"/\"):\n            if self.request.method in (\"GET\", \"HEAD\"):\n                uri = self.request.path.rstrip(\"/\")\n                if uri:  # don't try to redirect '/' to ''\n                    if self.request.query:\n                        uri += \"?\" + self.request.query\n                    self.redirect(uri, permanent=True)\n                    return\n            else:\n                raise HTTPError(404)\n        return method(self, *args, **kwargs)\n    return wrapper\n\n\ndef addslash(method):\n    \"\"\"Use this decorator to add a missing trailing slash to the request path.\n\n    For example, a request to ``/foo`` would redirect to ``/foo/`` with this\n    decorator. Your request handler mapping should use a regular expression\n    like ``r'/foo/?'`` in conjunction with using the decorator.\n    \"\"\"\n    @functools.wraps(method)\n    def wrapper(self, *args, **kwargs):\n        if not self.request.path.endswith(\"/\"):\n            if self.request.method in (\"GET\", \"HEAD\"):\n                uri = self.request.path + \"/\"\n                if self.request.query:\n                    uri += \"?\" + self.request.query\n                self.redirect(uri, permanent=True)\n                return\n            raise HTTPError(404)\n        return method(self, *args, **kwargs)\n    return wrapper\n\n\nclass Application(object):\n    \"\"\"A collection of request handlers that make up a web application.\n\n    Instances of this class are callable and can be passed directly to\n    HTTPServer to serve the application::\n\n        application = web.Application([\n            (r\"/\", MainPageHandler),\n        ])\n        http_server = httpserver.HTTPServer(application)\n        http_server.listen(8080)\n        ioloop.IOLoop.instance().start()\n\n    The constructor for this class takes in a list of `URLSpec` objects\n    or (regexp, request_class) tuples. When we receive requests, we\n    iterate over the list in order and instantiate an instance of the\n    first request class whose regexp matches the request path.\n\n    Each tuple can contain an optional third element, which should be\n    a dictionary if it is present. That dictionary is passed as\n    keyword arguments to the contructor of the handler. This pattern\n    is used for the `StaticFileHandler` in this example (note that a\n    `StaticFileHandler` can be installed automatically with the\n    static_path setting described below)::\n\n        application = web.Application([\n            (r\"/static/(.*)\", web.StaticFileHandler, {\"path\": \"/var/www\"}),\n        ])\n\n    We support virtual hosts with the `add_handlers` method, which takes in\n    a host regular expression as the first argument::\n\n        application.add_handlers(r\"www\\.myhost\\.com\", [\n            (r\"/article/([0-9]+)\", ArticleHandler),\n        ])\n\n    You can serve static files by sending the ``static_path`` setting\n    as a keyword argument. We will serve those files from the\n    ``/static/`` URI (this is configurable with the\n    ``static_url_prefix`` setting), and we will serve ``/favicon.ico``\n    and ``/robots.txt`` from the same directory.  A custom subclass of\n    `StaticFileHandler` can be specified with the\n    ``static_handler_class`` setting.\n    \"\"\"\n    def __init__(self, handlers=None, default_host=\"\", transforms=None,\n                 wsgi=False, **settings):\n        if transforms is None:\n            self.transforms = []\n            if settings.get(\"gzip\"):\n                self.transforms.append(GZipContentEncoding)\n            self.transforms.append(ChunkedTransferEncoding)\n        else:\n            self.transforms = transforms\n        self.handlers = []\n        self.named_handlers = {}\n        self.default_host = default_host\n        self.settings = settings\n        self.ui_modules = {'linkify': _linkify,\n                           'xsrf_form_html': _xsrf_form_html,\n                           'Template': TemplateModule,\n                           }\n        self.ui_methods = {}\n        self._wsgi = wsgi\n        self._load_ui_modules(settings.get(\"ui_modules\", {}))\n        self._load_ui_methods(settings.get(\"ui_methods\", {}))\n        if self.settings.get(\"static_path\"):\n            path = self.settings[\"static_path\"]\n            handlers = list(handlers or [])\n            static_url_prefix = settings.get(\"static_url_prefix\",\n                                             \"/static/\")\n            static_handler_class = settings.get(\"static_handler_class\",\n                                                StaticFileHandler)\n            static_handler_args = settings.get(\"static_handler_args\", {})\n            static_handler_args['path'] = path\n            for pattern in [re.escape(static_url_prefix) + r\"(.*)\",\n                            r\"/(favicon\\.ico)\", r\"/(robots\\.txt)\"]:\n                handlers.insert(0, (pattern, static_handler_class,\n                                    static_handler_args))\n        if handlers:\n            self.add_handlers(\".*$\", handlers)\n\n        # Automatically reload modified modules\n        if self.settings.get(\"debug\") and not wsgi:\n            from tornado import autoreload\n            autoreload.start()\n\n    def listen(self, port, address=\"\", **kwargs):\n        \"\"\"Starts an HTTP server for this application on the given port.\n\n        This is a convenience alias for creating an `.HTTPServer`\n        object and calling its listen method.  Keyword arguments not\n        supported by `HTTPServer.listen <.TCPServer.listen>` are passed to the\n        `.HTTPServer` constructor.  For advanced uses\n        (e.g. multi-process mode), do not use this method; create an\n        `.HTTPServer` and call its\n        `.TCPServer.bind`/`.TCPServer.start` methods directly.\n\n        Note that after calling this method you still need to call\n        ``IOLoop.instance().start()`` to start the server.\n        \"\"\"\n        # import is here rather than top level because HTTPServer\n        # is not importable on appengine\n        from tornado.httpserver import HTTPServer\n        server = HTTPServer(self, **kwargs)\n        server.listen(port, address)\n\n    def add_handlers(self, host_pattern, host_handlers):\n        \"\"\"Appends the given handlers to our handler list.\n\n        Host patterns are processed sequentially in the order they were\n        added. All matching patterns will be considered.\n        \"\"\"\n        if not host_pattern.endswith(\"$\"):\n            host_pattern += \"$\"\n        handlers = []\n        # The handlers with the wildcard host_pattern are a special\n        # case - they're added in the constructor but should have lower\n        # precedence than the more-precise handlers added later.\n        # If a wildcard handler group exists, it should always be last\n        # in the list, so insert new groups just before it.\n        if self.handlers and self.handlers[-1][0].pattern == '.*$':\n            self.handlers.insert(-1, (re.compile(host_pattern), handlers))\n        else:\n            self.handlers.append((re.compile(host_pattern), handlers))\n\n        for spec in host_handlers:\n            if isinstance(spec, (tuple, list)):\n                assert len(spec) in (2, 3)\n                pattern = spec[0]\n                handler = spec[1]\n\n                if isinstance(handler, str):\n                    # import the Module and instantiate the class\n                    # Must be a fully qualified name (module.ClassName)\n                    handler = import_object(handler)\n\n                if len(spec) == 3:\n                    kwargs = spec[2]\n                else:\n                    kwargs = {}\n                spec = URLSpec(pattern, handler, kwargs)\n            handlers.append(spec)\n            if spec.name:\n                if spec.name in self.named_handlers:\n                    app_log.warning(\n                        \"Multiple handlers named %s; replacing previous value\",\n                        spec.name)\n                self.named_handlers[spec.name] = spec\n\n    def add_transform(self, transform_class):\n        self.transforms.append(transform_class)\n\n    def _get_host_handlers(self, request):\n        host = request.host.lower().split(':')[0]\n        matches = []\n        for pattern, handlers in self.handlers:\n            if pattern.match(host):\n                matches.extend(handlers)\n        # Look for default host if not behind load balancer (for debugging)\n        if not matches and \"X-Real-Ip\" not in request.headers:\n            for pattern, handlers in self.handlers:\n                if pattern.match(self.default_host):\n                    matches.extend(handlers)\n        return matches or None\n\n    def _load_ui_methods(self, methods):\n        if isinstance(methods, types.ModuleType):\n            self._load_ui_methods(dict((n, getattr(methods, n))\n                                       for n in dir(methods)))\n        elif isinstance(methods, list):\n            for m in methods:\n                self._load_ui_methods(m)\n        else:\n            for name, fn in methods.items():\n                if not name.startswith(\"_\") and hasattr(fn, \"__call__\") \\\n                        and name[0].lower() == name[0]:\n                    self.ui_methods[name] = fn\n\n    def _load_ui_modules(self, modules):\n        if isinstance(modules, types.ModuleType):\n            self._load_ui_modules(dict((n, getattr(modules, n))\n                                       for n in dir(modules)))\n        elif isinstance(modules, list):\n            for m in modules:\n                self._load_ui_modules(m)\n        else:\n            assert isinstance(modules, dict)\n            for name, cls in modules.items():\n                try:\n                    if issubclass(cls, UIModule):\n                        self.ui_modules[name] = cls\n                except TypeError:\n                    pass\n\n    def __call__(self, request):\n        \"\"\"Called by HTTPServer to execute the request.\"\"\"\n        transforms = [t(request) for t in self.transforms]\n        handler = None\n        args = []\n        kwargs = {}\n        handlers = self._get_host_handlers(request)\n        if not handlers:\n            handler = RedirectHandler(\n                self, request, url=\"http://\" + self.default_host + \"/\")\n        else:\n            for spec in handlers:\n                match = spec.regex.match(request.path)\n                if match:\n                    handler = spec.handler_class(self, request, **spec.kwargs)\n                    if spec.regex.groups:\n                        # None-safe wrapper around url_unescape to handle\n                        # unmatched optional groups correctly\n                        def unquote(s):\n                            if s is None:\n                                return s\n                            return escape.url_unescape(s, encoding=None,\n                                                       plus=False)\n                        # Pass matched groups to the handler.  Since\n                        # match.groups() includes both named and unnamed groups,\n                        # we want to use either groups or groupdict but not both.\n                        # Note that args are passed as bytes so the handler can\n                        # decide what encoding to use.\n\n                        if spec.regex.groupindex:\n                            kwargs = dict(\n                                (str(k), unquote(v))\n                                for (k, v) in match.groupdict().items())\n                        else:\n                            args = [unquote(s) for s in match.groups()]\n                    break\n            if not handler:\n                handler = ErrorHandler(self, request, status_code=404)\n\n        # In debug mode, re-compile templates and reload static files on every\n        # request so you don't need to restart to see changes\n        if self.settings.get(\"debug\"):\n            with RequestHandler._template_loader_lock:\n                for loader in RequestHandler._template_loaders.values():\n                    loader.reset()\n            StaticFileHandler.reset()\n\n        handler._execute(transforms, *args, **kwargs)\n        return handler\n\n    def reverse_url(self, name, *args):\n        \"\"\"Returns a URL path for handler named ``name``\n\n        The handler must be added to the application as a named `URLSpec`.\n\n        Args will be substituted for capturing groups in the `URLSpec` regex.\n        They will be converted to strings if necessary, encoded as utf8,\n        and url-escaped.\n        \"\"\"\n        if name in self.named_handlers:\n            return self.named_handlers[name].reverse(*args)\n        raise KeyError(\"%s not found in named urls\" % name)\n\n    def log_request(self, handler):\n        \"\"\"Writes a completed HTTP request to the logs.\n\n        By default writes to the python root logger.  To change\n        this behavior either subclass Application and override this method,\n        or pass a function in the application settings dictionary as\n        ``log_function``.\n        \"\"\"\n        if \"log_function\" in self.settings:\n            self.settings[\"log_function\"](handler)\n            return\n        if handler.get_status() < 400:\n            log_method = access_log.info\n        elif handler.get_status() < 500:\n            log_method = access_log.warning\n        else:\n            log_method = access_log.error\n        request_time = 1000.0 * handler.request.request_time()\n        log_method(\"%d %s %.2fms\", handler.get_status(),\n                   handler._request_summary(), request_time)\n\n\nclass HTTPError(Exception):\n    \"\"\"An exception that will turn into an HTTP error response.\n\n    Raising an `HTTPError` is a convenient alternative to calling\n    `RequestHandler.send_error` since it automatically ends the\n    current function.\n\n    :arg int status_code: HTTP status code.  Must be listed in\n        `httplib.responses <http.client.responses>` unless the ``reason``\n        keyword argument is given.\n    :arg string log_message: Message to be written to the log for this error\n        (will not be shown to the user unless the `Application` is in debug\n        mode).  May contain ``%s``-style placeholders, which will be filled\n        in with remaining positional parameters.\n    :arg string reason: Keyword-only argument.  The HTTP \"reason\" phrase\n        to pass in the status line along with ``status_code``.  Normally\n        determined automatically from ``status_code``, but can be used\n        to use a non-standard numeric code.\n    \"\"\"\n    def __init__(self, status_code, log_message=None, *args, **kwargs):\n        self.status_code = status_code\n        self.log_message = log_message\n        self.args = args\n        self.reason = kwargs.get('reason', None)\n\n    def __str__(self):\n        message = \"HTTP %d: %s\" % (\n            self.status_code,\n            self.reason or httputil.responses.get(self.status_code, 'Unknown'))\n        if self.log_message:\n            return message + \" (\" + (self.log_message % self.args) + \")\"\n        else:\n            return message\n\n\nclass MissingArgumentError(HTTPError):\n    \"\"\"Exception raised by `RequestHandler.get_argument`.\n\n    This is a subclass of `HTTPError`, so if it is uncaught a 400 response\n    code will be used instead of 500 (and a stack trace will not be logged).\n\n    .. versionadded:: 3.1\n    \"\"\"\n    def __init__(self, arg_name):\n        super(MissingArgumentError, self).__init__(\n            400, 'Missing argument %s' % arg_name)\n        self.arg_name = arg_name\n\n\nclass ErrorHandler(RequestHandler):\n    \"\"\"Generates an error response with ``status_code`` for all requests.\"\"\"\n    def initialize(self, status_code):\n        self.set_status(status_code)\n\n    def prepare(self):\n        raise HTTPError(self._status_code)\n\n    def check_xsrf_cookie(self):\n        # POSTs to an ErrorHandler don't actually have side effects,\n        # so we don't need to check the xsrf token.  This allows POSTs\n        # to the wrong url to return a 404 instead of 403.\n        pass\n\n\nclass RedirectHandler(RequestHandler):\n    \"\"\"Redirects the client to the given URL for all GET requests.\n\n    You should provide the keyword argument ``url`` to the handler, e.g.::\n\n        application = web.Application([\n            (r\"/oldpath\", web.RedirectHandler, {\"url\": \"/newpath\"}),\n        ])\n    \"\"\"\n    def initialize(self, url, permanent=True):\n        self._url = url\n        self._permanent = permanent\n\n    def get(self):\n        self.redirect(self._url, permanent=self._permanent)\n\n\nclass StaticFileHandler(RequestHandler):\n    \"\"\"A simple handler that can serve static content from a directory.\n\n    A `StaticFileHandler` is configured automatically if you pass the\n    ``static_path`` keyword argument to `Application`.  This handler\n    can be customized with the ``static_url_prefix``, ``static_handler_class``,\n    and ``static_handler_args`` settings.\n\n    To map an additional path to this handler for a static data directory\n    you would add a line to your application like::\n\n        application = web.Application([\n            (r\"/content/(.*)\", web.StaticFileHandler, {\"path\": \"/var/www\"}),\n        ])\n\n    The handler constructor requires a ``path`` argument, which specifies the\n    local root directory of the content to be served.\n\n    Note that a capture group in the regex is required to parse the value for\n    the ``path`` argument to the get() method (different than the constructor\n    argument above); see `URLSpec` for details.\n\n    To maximize the effectiveness of browser caching, this class supports\n    versioned urls (by default using the argument ``?v=``).  If a version\n    is given, we instruct the browser to cache this file indefinitely.\n    `make_static_url` (also available as `RequestHandler.static_url`) can\n    be used to construct a versioned url.\n\n    This handler is intended primarily for use in development and light-duty\n    file serving; for heavy traffic it will be more efficient to use\n    a dedicated static file server (such as nginx or Apache).  We support\n    the HTTP ``Accept-Ranges`` mechanism to return partial content (because\n    some browsers require this functionality to be present to seek in\n    HTML5 audio or video), but this handler should not be used with\n    files that are too large to fit comfortably in memory.\n\n    **Subclassing notes**\n\n    This class is designed to be extensible by subclassing, but because\n    of the way static urls are generated with class methods rather than\n    instance methods, the inheritance patterns are somewhat unusual.\n    Be sure to use the ``@classmethod`` decorator when overriding a\n    class method.  Instance methods may use the attributes ``self.path``\n    ``self.absolute_path``, and ``self.modified``.\n\n    To change the way static urls are generated (e.g. to match the behavior\n    of another server or CDN), override `make_static_url`, `parse_url_path`,\n    `get_cache_time`, and/or `get_version`.\n\n    To replace all interaction with the filesystem (e.g. to serve\n    static content from a database), override `get_content`,\n    `get_content_size`, `get_modified_time`, `get_absolute_path`, and\n    `validate_absolute_path`.\n\n    .. versionchanged:: 3.1\n       Many of the methods for subclasses were added in Tornado 3.1.\n    \"\"\"\n    CACHE_MAX_AGE = 86400 * 365 * 10  # 10 years\n\n    _static_hashes = {}\n    _lock = threading.Lock()  # protects _static_hashes\n\n    def initialize(self, path, default_filename=None):\n        self.root = path\n        self.default_filename = default_filename\n\n    @classmethod\n    def reset(cls):\n        with cls._lock:\n            cls._static_hashes = {}\n\n    def head(self, path):\n        self.get(path, include_body=False)\n\n    def get(self, path, include_body=True):\n        # Set up our path instance variables.\n        self.path = self.parse_url_path(path)\n        del path  # make sure we don't refer to path instead of self.path again\n        absolute_path = self.get_absolute_path(self.root, self.path)\n        self.absolute_path = self.validate_absolute_path(\n            self.root, absolute_path)\n        if self.absolute_path is None:\n            return\n\n        self.modified = self.get_modified_time()\n        self.set_headers()\n\n        if self.should_return_304():\n            self.set_status(304)\n            return\n\n        request_range = None\n        range_header = self.request.headers.get(\"Range\")\n        if range_header:\n            # As per RFC 2616 14.16, if an invalid Range header is specified,\n            # the request will be treated as if the header didn't exist.\n            request_range = httputil._parse_request_range(range_header)\n\n        if request_range:\n            start, end = request_range\n            size = self.get_content_size()\n            if (start is not None and start >= size) or end == 0:\n                # As per RFC 2616 14.35.1, a range is not satisfiable only: if\n                # the first requested byte is equal to or greater than the\n                # content, or when a suffix with length 0 is specified\n                self.set_status(416)  # Range Not Satisfiable\n                self.set_header(\"Content-Type\", \"text/plain\")\n                self.set_header(\"Content-Range\", \"bytes */%s\" %(size, ))\n                return\n            if start is not None and start < 0:\n                start += size\n            if end is not None and end > size:\n                # Clients sometimes blindly use a large range to limit their\n                # download size; cap the endpoint at the actual file size.\n                end = size\n            # Note: only return HTTP 206 if less than the entire range has been\n            # requested. Not only is this semantically correct, but Chrome\n            # refuses to play audio if it gets an HTTP 206 in response to\n            # ``Range: bytes=0-``.\n            if size != (end or size) - (start or 0):\n                self.set_status(206)  # Partial Content\n                self.set_header(\"Content-Range\",\n                                httputil._get_content_range(start, end, size))\n        else:\n            start = end = None\n        content = self.get_content(self.absolute_path, start, end)\n        if isinstance(content, bytes_type):\n            content = [content]\n        content_length = 0\n        for chunk in content:\n            if include_body:\n                self.write(chunk)\n            else:\n                content_length += len(chunk)\n        if not include_body:\n            assert self.request.method == \"HEAD\"\n            self.set_header(\"Content-Length\", content_length)\n\n    def compute_etag(self):\n        \"\"\"Sets the ``Etag`` header based on static url version.\n\n        This allows efficient ``If-None-Match`` checks against cached\n        versions, and sends the correct ``Etag`` for a partial response\n        (i.e. the same ``Etag`` as the full file).\n\n        .. versionadded:: 3.1\n        \"\"\"\n        version_hash = self._get_cached_version(self.absolute_path)\n        if not version_hash:\n            return None\n        return '\"%s\"' % (version_hash, )\n\n    def set_headers(self):\n        \"\"\"Sets the content and caching headers on the response.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        self.set_header(\"Accept-Ranges\", \"bytes\")\n        self.set_etag_header()\n\n        if self.modified is not None:\n            self.set_header(\"Last-Modified\", self.modified)\n\n        content_type = self.get_content_type()\n        if content_type:\n            self.set_header(\"Content-Type\", content_type)\n\n        cache_time = self.get_cache_time(self.path, self.modified, content_type)\n        if cache_time > 0:\n            self.set_header(\"Expires\", datetime.datetime.utcnow() +\n                            datetime.timedelta(seconds=cache_time))\n            self.set_header(\"Cache-Control\", \"max-age=\" + str(cache_time))\n\n        self.set_extra_headers(self.path)\n\n    def should_return_304(self):\n        \"\"\"Returns True if the headers indicate that we should return 304.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        if self.check_etag_header():\n            return True\n\n        # Check the If-Modified-Since, and don't send the result if the\n        # content has not been modified\n        ims_value = self.request.headers.get(\"If-Modified-Since\")\n        if ims_value is not None:\n            date_tuple = email.utils.parsedate(ims_value)\n            if date_tuple is not None:\n                if_since = datetime.datetime(*date_tuple[:6])\n                if if_since >= self.modified:\n                    return True\n\n        return False\n\n    @classmethod\n    def get_absolute_path(cls, root, path):\n        \"\"\"Returns the absolute location of ``path`` relative to ``root``.\n\n        ``root`` is the path configured for this `StaticFileHandler`\n        (in most cases the ``static_path`` `Application` setting).\n\n        This class method may be overridden in subclasses.  By default\n        it returns a filesystem path, but other strings may be used\n        as long as they are unique and understood by the subclass's\n        overridden `get_content`.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        abspath = os.path.abspath(os.path.join(root, path))\n        return abspath\n\n    def validate_absolute_path(self, root, absolute_path):\n        \"\"\"Validate and return the absolute path.\n\n        ``root`` is the configured path for the `StaticFileHandler`,\n        and ``path`` is the result of `get_absolute_path`\n\n        This is an instance method called during request processing,\n        so it may raise `HTTPError` or use methods like\n        `RequestHandler.redirect` (return None after redirecting to\n        halt further processing).  This is where 404 errors for missing files\n        are generated.\n\n        This method may modify the path before returning it, but note that\n        any such modifications will not be understood by `make_static_url`.\n\n        In instance methods, this method's result is available as\n        ``self.absolute_path``.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        root = os.path.abspath(root)\n        # os.path.abspath strips a trailing /\n        # it needs to be temporarily added back for requests to root/\n        if not (absolute_path + os.path.sep).startswith(root):\n            raise HTTPError(403, \"%s is not in root static directory\",\n                            self.path)\n        if (os.path.isdir(absolute_path) and\n                self.default_filename is not None):\n            # need to look at the request.path here for when path is empty\n            # but there is some prefix to the path that was already\n            # trimmed by the routing\n            if not self.request.path.endswith(\"/\"):\n                self.redirect(self.request.path + \"/\", permanent=True)\n                return\n            absolute_path = os.path.join(absolute_path, self.default_filename)\n        if not os.path.exists(absolute_path):\n            raise HTTPError(404)\n        if not os.path.isfile(absolute_path):\n            raise HTTPError(403, \"%s is not a file\", self.path)\n        return absolute_path\n\n    @classmethod\n    def get_content(cls, abspath, start=None, end=None):\n        \"\"\"Retrieve the content of the requested resource which is located\n        at the given absolute path.\n\n        This class method may be overridden by subclasses.  Note that its\n        signature is different from other overridable class methods\n        (no ``settings`` argument); this is deliberate to ensure that\n        ``abspath`` is able to stand on its own as a cache key.\n\n        This method should either return a byte string or an iterator\n        of byte strings.  The latter is preferred for large files\n        as it helps reduce memory fragmentation.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        with open(abspath, \"rb\") as file:\n            if start is not None:\n                file.seek(start)\n            if end is not None:\n                remaining = end - (start or 0)\n            else:\n                remaining = None\n            while True:\n                chunk_size = 64 * 1024\n                if remaining is not None and remaining < chunk_size:\n                    chunk_size = remaining\n                chunk = file.read(chunk_size)\n                if chunk:\n                    if remaining is not None:\n                        remaining -= len(chunk)\n                    yield chunk\n                else:\n                    if remaining is not None:\n                        assert remaining == 0\n                    return\n\n    @classmethod\n    def get_content_version(cls, abspath):\n        \"\"\"Returns a version string for the resource at the given path.\n\n        This class method may be overridden by subclasses.  The\n        default implementation is a hash of the file's contents.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        data = cls.get_content(abspath)\n        hasher = hashlib.md5()\n        if isinstance(data, bytes_type):\n            hasher.update(data)\n        else:\n            for chunk in data:\n                hasher.update(chunk)\n        return hasher.hexdigest()\n\n    def _stat(self):\n        if not hasattr(self, '_stat_result'):\n            self._stat_result = os.stat(self.absolute_path)\n        return self._stat_result\n\n    def get_content_size(self):\n        \"\"\"Retrieve the total size of the resource at the given path.\n\n        This method may be overridden by subclasses. It will only\n        be called if a partial result is requested from `get_content`\n\n        .. versionadded:: 3.1\n        \"\"\"\n        stat_result = self._stat()\n        return stat_result[stat.ST_SIZE]\n\n    def get_modified_time(self):\n        \"\"\"Returns the time that ``self.absolute_path`` was last modified.\n\n        May be overridden in subclasses.  Should return a `~datetime.datetime`\n        object or None.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        stat_result = self._stat()\n        modified = datetime.datetime.utcfromtimestamp(stat_result[stat.ST_MTIME])\n        return modified\n\n    def get_content_type(self):\n        \"\"\"Returns the ``Content-Type`` header to be used for this request.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        mime_type, encoding = mimetypes.guess_type(self.absolute_path)\n        return mime_type\n\n    def set_extra_headers(self, path):\n        \"\"\"For subclass to add extra headers to the response\"\"\"\n        pass\n\n    def get_cache_time(self, path, modified, mime_type):\n        \"\"\"Override to customize cache control behavior.\n\n        Return a positive number of seconds to make the result\n        cacheable for that amount of time or 0 to mark resource as\n        cacheable for an unspecified amount of time (subject to\n        browser heuristics).\n\n        By default returns cache expiry of 10 years for resources requested\n        with ``v`` argument.\n        \"\"\"\n        return self.CACHE_MAX_AGE if \"v\" in self.request.arguments else 0\n\n    @classmethod\n    def make_static_url(cls, settings, path, include_version=True):\n        \"\"\"Constructs a versioned url for the given path.\n\n        This method may be overridden in subclasses (but note that it\n        is a class method rather than an instance method).  Subclasses\n        are only required to implement the signature\n        ``make_static_url(cls, settings, path)``; other keyword\n        arguments may be passed through `~RequestHandler.static_url`\n        but are not standard.\n\n        ``settings`` is the `Application.settings` dictionary.  ``path``\n        is the static path being requested.  The url returned should be\n        relative to the current host.\n\n        ``include_version`` determines whether the generated URL should\n        include the query string containing the version hash of the\n        file corresponding to the given ``path``.\n\n        \"\"\"\n        url = settings.get('static_url_prefix', '/static/') + path\n        if not include_version:\n            return url\n\n        version_hash = cls.get_version(settings, path)\n        if not version_hash:\n            return url\n\n        return '%s?v=%s' % (url, version_hash)\n\n    def parse_url_path(self, url_path):\n        \"\"\"Converts a static URL path into a filesystem path.\n\n        ``url_path`` is the path component of the URL with\n        ``static_url_prefix`` removed.  The return value should be\n        filesystem path relative to ``static_path``.\n\n        This is the inverse of `make_static_url`.\n        \"\"\"\n        if os.path.sep != \"/\":\n            url_path = url_path.replace(\"/\", os.path.sep)\n        return url_path\n\n    @classmethod\n    def get_version(cls, settings, path):\n        \"\"\"Generate the version string to be used in static URLs.\n\n        ``settings`` is the `Application.settings` dictionary and ``path``\n        is the relative location of the requested asset on the filesystem.\n        The returned value should be a string, or ``None`` if no version\n        could be determined.\n\n        .. versionchanged:: 3.1\n           This method was previously recommended for subclasses to override;\n           `get_content_version` is now preferred as it allows the base\n           class to handle caching of the result.\n        \"\"\"\n        abs_path = cls.get_absolute_path(settings['static_path'], path)\n        return cls._get_cached_version(abs_path)\n\n    @classmethod\n    def _get_cached_version(cls, abs_path):\n        with cls._lock:\n            hashes = cls._static_hashes\n            if abs_path not in hashes:\n                try:\n                    hashes[abs_path] = cls.get_content_version(abs_path)\n                except Exception:\n                    gen_log.error(\"Could not open static file %r\", abs_path)\n                    hashes[abs_path] = None\n            hsh = hashes.get(abs_path)\n            if hsh:\n                return hsh\n        return None\n\n\nclass FallbackHandler(RequestHandler):\n    \"\"\"A `RequestHandler` that wraps another HTTP server callback.\n\n    The fallback is a callable object that accepts an\n    `~.httpserver.HTTPRequest`, such as an `Application` or\n    `tornado.wsgi.WSGIContainer`.  This is most useful to use both\n    Tornado ``RequestHandlers`` and WSGI in the same server.  Typical\n    usage::\n\n        wsgi_app = tornado.wsgi.WSGIContainer(\n            django.core.handlers.wsgi.WSGIHandler())\n        application = tornado.web.Application([\n            (r\"/foo\", FooHandler),\n            (r\".*\", FallbackHandler, dict(fallback=wsgi_app),\n        ])\n    \"\"\"\n    def initialize(self, fallback):\n        self.fallback = fallback\n\n    def prepare(self):\n        self.fallback(self.request)\n        self._finished = True\n\n\nclass OutputTransform(object):\n    \"\"\"A transform modifies the result of an HTTP request (e.g., GZip encoding)\n\n    A new transform instance is created for every request. See the\n    ChunkedTransferEncoding example below if you want to implement a\n    new Transform.\n    \"\"\"\n    def __init__(self, request):\n        pass\n\n    def transform_first_chunk(self, status_code, headers, chunk, finishing):\n        return status_code, headers, chunk\n\n    def transform_chunk(self, chunk, finishing):\n        return chunk\n\n\nclass GZipContentEncoding(OutputTransform):\n    \"\"\"Applies the gzip content encoding to the response.\n\n    See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11\n    \"\"\"\n    CONTENT_TYPES = set([\n        \"text/plain\", \"text/html\", \"text/css\", \"text/xml\", \"application/javascript\",\n        \"application/x-javascript\", \"application/xml\", \"application/atom+xml\",\n        \"text/javascript\", \"application/json\", \"application/xhtml+xml\"])\n    MIN_LENGTH = 5\n\n    def __init__(self, request):\n        self._gzipping = request.supports_http_1_1() and \\\n            \"gzip\" in request.headers.get(\"Accept-Encoding\", \"\")\n\n    def transform_first_chunk(self, status_code, headers, chunk, finishing):\n        if 'Vary' in headers:\n            headers['Vary'] += b', Accept-Encoding'\n        else:\n            headers['Vary'] = b'Accept-Encoding'\n        if self._gzipping:\n            ctype = _unicode(headers.get(\"Content-Type\", \"\")).split(\";\")[0]\n            self._gzipping = (ctype in self.CONTENT_TYPES) and \\\n                (not finishing or len(chunk) >= self.MIN_LENGTH) and \\\n                (finishing or \"Content-Length\" not in headers) and \\\n                (\"Content-Encoding\" not in headers)\n        if self._gzipping:\n            headers[\"Content-Encoding\"] = \"gzip\"\n            self._gzip_value = BytesIO()\n            self._gzip_file = gzip.GzipFile(mode=\"w\", fileobj=self._gzip_value)\n            chunk = self.transform_chunk(chunk, finishing)\n            if \"Content-Length\" in headers:\n                headers[\"Content-Length\"] = str(len(chunk))\n        return status_code, headers, chunk\n\n    def transform_chunk(self, chunk, finishing):\n        if self._gzipping:\n            self._gzip_file.write(chunk)\n            if finishing:\n                self._gzip_file.close()\n            else:\n                self._gzip_file.flush()\n            chunk = self._gzip_value.getvalue()\n            self._gzip_value.truncate(0)\n            self._gzip_value.seek(0)\n        return chunk\n\n\nclass ChunkedTransferEncoding(OutputTransform):\n    \"\"\"Applies the chunked transfer encoding to the response.\n\n    See http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.6.1\n    \"\"\"\n    def __init__(self, request):\n        self._chunking = request.supports_http_1_1()\n\n    def transform_first_chunk(self, status_code, headers, chunk, finishing):\n        # 304 responses have no body (not even a zero-length body), and so\n        # should not have either Content-Length or Transfer-Encoding headers.\n        if self._chunking and status_code != 304:\n            # No need to chunk the output if a Content-Length is specified\n            if \"Content-Length\" in headers or \"Transfer-Encoding\" in headers:\n                self._chunking = False\n            else:\n                headers[\"Transfer-Encoding\"] = \"chunked\"\n                chunk = self.transform_chunk(chunk, finishing)\n        return status_code, headers, chunk\n\n    def transform_chunk(self, block, finishing):\n        if self._chunking:\n            # Don't write out empty chunks because that means END-OF-STREAM\n            # with chunked encoding\n            if block:\n                block = utf8(\"%x\" % len(block)) + b\"\\r\\n\" + block + b\"\\r\\n\"\n            if finishing:\n                block += b\"0\\r\\n\\r\\n\"\n        return block\n\n\ndef authenticated(method):\n    \"\"\"Decorate methods with this to require that the user be logged in.\n\n    If the user is not logged in, they will be redirected to the configured\n    `login url <RequestHandler.get_login_url>`.\n    \"\"\"\n    @functools.wraps(method)\n    def wrapper(self, *args, **kwargs):\n        if not self.current_user:\n            if self.request.method in (\"GET\", \"HEAD\"):\n                url = self.get_login_url()\n                if \"?\" not in url:\n                    if urlparse.urlsplit(url).scheme:\n                        # if login url is absolute, make next absolute too\n                        next_url = self.request.full_url()\n                    else:\n                        next_url = self.request.uri\n                    url += \"?\" + urlencode(dict(next=next_url))\n                self.redirect(url)\n                return\n            raise HTTPError(403)\n        return method(self, *args, **kwargs)\n    return wrapper\n\n\nclass UIModule(object):\n    \"\"\"A re-usable, modular UI unit on a page.\n\n    UI modules often execute additional queries, and they can include\n    additional CSS and JavaScript that will be included in the output\n    page, which is automatically inserted on page render.\n    \"\"\"\n    def __init__(self, handler):\n        self.handler = handler\n        self.request = handler.request\n        self.ui = handler.ui\n        self.locale = handler.locale\n\n    @property\n    def current_user(self):\n        return self.handler.current_user\n\n    def render(self, *args, **kwargs):\n        \"\"\"Overridden in subclasses to return this module's output.\"\"\"\n        raise NotImplementedError()\n\n    def embedded_javascript(self):\n        \"\"\"Returns a JavaScript string that will be embedded in the page.\"\"\"\n        return None\n\n    def javascript_files(self):\n        \"\"\"Returns a list of JavaScript files required by this module.\"\"\"\n        return None\n\n    def embedded_css(self):\n        \"\"\"Returns a CSS string that will be embedded in the page.\"\"\"\n        return None\n\n    def css_files(self):\n        \"\"\"Returns a list of CSS files required by this module.\"\"\"\n        return None\n\n    def html_head(self):\n        \"\"\"Returns a CSS string that will be put in the <head/> element\"\"\"\n        return None\n\n    def html_body(self):\n        \"\"\"Returns an HTML string that will be put in the <body/> element\"\"\"\n        return None\n\n    def render_string(self, path, **kwargs):\n        \"\"\"Renders a template and returns it as a string.\"\"\"\n        return self.handler.render_string(path, **kwargs)\n\n\nclass _linkify(UIModule):\n    def render(self, text, **kwargs):\n        return escape.linkify(text, **kwargs)\n\n\nclass _xsrf_form_html(UIModule):\n    def render(self):\n        return self.handler.xsrf_form_html()\n\n\nclass TemplateModule(UIModule):\n    \"\"\"UIModule that simply renders the given template.\n\n    {% module Template(\"foo.html\") %} is similar to {% include \"foo.html\" %},\n    but the module version gets its own namespace (with kwargs passed to\n    Template()) instead of inheriting the outer template's namespace.\n\n    Templates rendered through this module also get access to UIModule's\n    automatic javascript/css features.  Simply call set_resources\n    inside the template and give it keyword arguments corresponding to\n    the methods on UIModule: {{ set_resources(js_files=static_url(\"my.js\")) }}\n    Note that these resources are output once per template file, not once\n    per instantiation of the template, so they must not depend on\n    any arguments to the template.\n    \"\"\"\n    def __init__(self, handler):\n        super(TemplateModule, self).__init__(handler)\n        # keep resources in both a list and a dict to preserve order\n        self._resource_list = []\n        self._resource_dict = {}\n\n    def render(self, path, **kwargs):\n        def set_resources(**kwargs):\n            if path not in self._resource_dict:\n                self._resource_list.append(kwargs)\n                self._resource_dict[path] = kwargs\n            else:\n                if self._resource_dict[path] != kwargs:\n                    raise ValueError(\"set_resources called with different \"\n                                     \"resources for the same template\")\n            return \"\"\n        return self.render_string(path, set_resources=set_resources,\n                                  **kwargs)\n\n    def _get_resources(self, key):\n        return (r[key] for r in self._resource_list if key in r)\n\n    def embedded_javascript(self):\n        return \"\\n\".join(self._get_resources(\"embedded_javascript\"))\n\n    def javascript_files(self):\n        result = []\n        for f in self._get_resources(\"javascript_files\"):\n            if isinstance(f, (unicode_type, bytes_type)):\n                result.append(f)\n            else:\n                result.extend(f)\n        return result\n\n    def embedded_css(self):\n        return \"\\n\".join(self._get_resources(\"embedded_css\"))\n\n    def css_files(self):\n        result = []\n        for f in self._get_resources(\"css_files\"):\n            if isinstance(f, (unicode_type, bytes_type)):\n                result.append(f)\n            else:\n                result.extend(f)\n        return result\n\n    def html_head(self):\n        return \"\".join(self._get_resources(\"html_head\"))\n\n    def html_body(self):\n        return \"\".join(self._get_resources(\"html_body\"))\n\n\nclass _UIModuleNamespace(object):\n    \"\"\"Lazy namespace which creates UIModule proxies bound to a handler.\"\"\"\n    def __init__(self, handler, ui_modules):\n        self.handler = handler\n        self.ui_modules = ui_modules\n\n    def __getitem__(self, key):\n        return self.handler._ui_module(key, self.ui_modules[key])\n\n    def __getattr__(self, key):\n        try:\n            return self[key]\n        except KeyError as e:\n            raise AttributeError(str(e))\n\n\nclass URLSpec(object):\n    \"\"\"Specifies mappings between URLs and handlers.\"\"\"\n    def __init__(self, pattern, handler_class, kwargs=None, name=None):\n        \"\"\"Parameters:\n\n        * ``pattern``: Regular expression to be matched.  Any groups\n          in the regex will be passed in to the handler's get/post/etc\n          methods as arguments.\n\n        * ``handler_class``: `RequestHandler` subclass to be invoked.\n\n        * ``kwargs`` (optional): A dictionary of additional arguments\n          to be passed to the handler's constructor.\n\n        * ``name`` (optional): A name for this handler.  Used by\n          `Application.reverse_url`.\n        \"\"\"\n        if not pattern.endswith('$'):\n            pattern += '$'\n        self.regex = re.compile(pattern)\n        assert len(self.regex.groupindex) in (0, self.regex.groups), \\\n            (\"groups in url regexes must either be all named or all \"\n             \"positional: %r\" % self.regex.pattern)\n        self.handler_class = handler_class\n        self.kwargs = kwargs or {}\n        self.name = name\n        self._path, self._group_count = self._find_groups()\n\n    def __repr__(self):\n        return '%s(%r, %s, kwargs=%r, name=%r)' % \\\n            (self.__class__.__name__, self.regex.pattern,\n             self.handler_class, self.kwargs, self.name)\n\n    def _find_groups(self):\n        \"\"\"Returns a tuple (reverse string, group count) for a url.\n\n        For example: Given the url pattern /([0-9]{4})/([a-z-]+)/, this method\n        would return ('/%s/%s/', 2).\n        \"\"\"\n        pattern = self.regex.pattern\n        if pattern.startswith('^'):\n            pattern = pattern[1:]\n        if pattern.endswith('$'):\n            pattern = pattern[:-1]\n\n        if self.regex.groups != pattern.count('('):\n            # The pattern is too complicated for our simplistic matching,\n            # so we can't support reversing it.\n            return (None, None)\n\n        pieces = []\n        for fragment in pattern.split('('):\n            if ')' in fragment:\n                paren_loc = fragment.index(')')\n                if paren_loc >= 0:\n                    pieces.append('%s' + fragment[paren_loc + 1:])\n            else:\n                pieces.append(fragment)\n\n        return (''.join(pieces), self.regex.groups)\n\n    def reverse(self, *args):\n        assert self._path is not None, \\\n            \"Cannot reverse url regex \" + self.regex.pattern\n        assert len(args) == self._group_count, \"required number of arguments \"\\\n            \"not found\"\n        if not len(args):\n            return self._path\n        converted_args = []\n        for a in args:\n            if not isinstance(a, (unicode_type, bytes_type)):\n                a = str(a)\n            converted_args.append(escape.url_escape(utf8(a), plus=False))\n        return self._path % tuple(converted_args)\n\nurl = URLSpec\n\n\nif hasattr(hmac, 'compare_digest'):  # python 3.3\n    _time_independent_equals = hmac.compare_digest\nelse:\n    def _time_independent_equals(a, b):\n        if len(a) != len(b):\n            return False\n        result = 0\n        if isinstance(a[0], int):  # python3 byte strings\n            for x, y in zip(a, b):\n                result |= x ^ y\n        else:  # python2\n            for x, y in zip(a, b):\n                result |= ord(x) ^ ord(y)\n        return result == 0\n\n\ndef create_signed_value(secret, name, value):\n    timestamp = utf8(str(int(time.time())))\n    value = base64.b64encode(utf8(value))\n    signature = _create_signature(secret, name, value, timestamp)\n    value = b\"|\".join([value, timestamp, signature])\n    return value\n\n\ndef decode_signed_value(secret, name, value, max_age_days=31):\n    if not value:\n        return None\n    parts = utf8(value).split(b\"|\")\n    if len(parts) != 3:\n        return None\n    signature = _create_signature(secret, name, parts[0], parts[1])\n    if not _time_independent_equals(parts[2], signature):\n        gen_log.warning(\"Invalid cookie signature %r\", value)\n        return None\n    timestamp = int(parts[1])\n    if timestamp < time.time() - max_age_days * 86400:\n        gen_log.warning(\"Expired cookie %r\", value)\n        return None\n    if timestamp > time.time() + 31 * 86400:\n        # _cookie_signature does not hash a delimiter between the\n        # parts of the cookie, so an attacker could transfer trailing\n        # digits from the payload to the timestamp without altering the\n        # signature.  For backwards compatibility, sanity-check timestamp\n        # here instead of modifying _cookie_signature.\n        gen_log.warning(\"Cookie timestamp in future; possible tampering %r\", value)\n        return None\n    if parts[1].startswith(b\"0\"):\n        gen_log.warning(\"Tampered cookie %r\", value)\n        return None\n    try:\n        return base64.b64decode(parts[0])\n    except Exception:\n        return None\n\n\ndef _create_signature(secret, *parts):\n    hash = hmac.new(utf8(secret), digestmod=hashlib.sha1)\n    for part in parts:\n        hash.update(utf8(part))\n    return utf8(hash.hexdigest())\n",
            "header": {
                "file": {
                    "path": "tornado/web.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "63f5514c",
                "new_commit_hash": "e09dda9b",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tornado/web.py"
            },
            "plus_file": {
                "path": "b/tornado/web.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 2309,
                            "length": 9
                        },
                        "new_range": {
                            "start": 2309,
                            "length": 12
                        },
                        "section": "class UIModule(object):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        self.handler = handler",
                                "type": "context"
                            },
                            {
                                "content": "        self.request = handler.request",
                                "type": "context"
                            },
                            {
                                "content": "        self.ui = handler.ui",
                                "type": "context"
                            },
                            {
                                "content": "        self.current_user = handler.current_user",
                                "type": "deleted"
                            },
                            {
                                "content": "        self.locale = handler.locale",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    @property",
                                "type": "added"
                            },
                            {
                                "content": "    def current_user(self):",
                                "type": "added"
                            },
                            {
                                "content": "        return self.handler.current_user",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def render(self, *args, **kwargs):",
                                "type": "context"
                            },
                            {
                                "content": "        \"\"\"Overridden in subclasses to return this module's output.\"\"\"",
                                "type": "context"
                            },
                            {
                                "content": "        raise NotImplementedError()",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/web.py",
                            "type": "method",
                            "name": "UIModule.__init__",
                            "content": "class UIModule(object):\n    \"\"\"A re-usable, modular UI unit on a page.\n\n    UI modules often execute additional queries, and they can include\n    additional CSS and JavaScript that will be included in the output\n    page, which is automatically inserted on page render.\n    \"\"\"\n    def __init__(self, handler):\n        self.handler = handler\n        self.request = handler.request\n        self.ui = handler.ui\n        self.current_user = handler.current_user\n        self.locale = handler.locale\n\n    def render(self, *args, **kwargs):\n        \"\"\"Overridden in subclasses to return this module's output.\"\"\"\n        raise NotImplementedError()\n\n    def embedded_javascript(self):\n        \"\"\"Returns a JavaScript string that will be embedded in the page.\"\"\"\n        return None\n\n    def javascript_files(self):\n        \"\"\"Returns a list of JavaScript files required by this module.\"\"\"\n        return None\n\n    def embedded_css(self):\n        \"\"\"Returns a CSS string that will be embedded in the page.\"\"\"\n        return None\n\n    def css_files(self):\n        \"\"\"Returns a list of CSS files required by this module.\"\"\"\n        return None\n\n    def html_head(self):\n        \"\"\"Returns a CSS string that will be put in the <head/> element\"\"\"\n        return None\n\n    def html_body(self):\n        \"\"\"Returns an HTML string that will be put in the <body/> element\"\"\"\n        return None\n\n    def render_string(self, path, **kwargs):\n        \"\"\"Renders a template and returns it as a string.\"\"\"\n        return self.handler.render_string(path, **kwargs)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 2308,
                            "end_lineno": 2313,
                            "parent": {
                                "file_name": "tornado/web.py",
                                "type": "class",
                                "name": "UIModule",
                                "content": "class UIModule(object):\n    \"\"\"A re-usable, modular UI unit on a page.\n\n    UI modules often execute additional queries, and they can include\n    additional CSS and JavaScript that will be included in the output\n    page, which is automatically inserted on page render.\n    \"\"\"\n    def __init__(self, handler):\n        self.handler = handler\n        self.request = handler.request\n        self.ui = handler.ui\n        self.current_user = handler.current_user\n        self.locale = handler.locale\n\n    def render(self, *args, **kwargs):\n        \"\"\"Overridden in subclasses to return this module's output.\"\"\"\n        raise NotImplementedError()\n\n    def embedded_javascript(self):\n        \"\"\"Returns a JavaScript string that will be embedded in the page.\"\"\"\n        return None\n\n    def javascript_files(self):\n        \"\"\"Returns a list of JavaScript files required by this module.\"\"\"\n        return None\n\n    def embedded_css(self):\n        \"\"\"Returns a CSS string that will be embedded in the page.\"\"\"\n        return None\n\n    def css_files(self):\n        \"\"\"Returns a list of CSS files required by this module.\"\"\"\n        return None\n\n    def html_head(self):\n        \"\"\"Returns a CSS string that will be put in the <head/> element\"\"\"\n        return None\n\n    def html_body(self):\n        \"\"\"Returns an HTML string that will be put in the <body/> element\"\"\"\n        return None\n\n    def render_string(self, path, **kwargs):\n        \"\"\"Renders a template and returns it as a string.\"\"\"\n        return self.handler.render_string(path, **kwargs)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 2301,
                                "end_lineno": 2345,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/web.py",
                            "type": "class",
                            "name": "UIModule",
                            "content": "class UIModule(object):\n    \"\"\"A re-usable, modular UI unit on a page.\n\n    UI modules often execute additional queries, and they can include\n    additional CSS and JavaScript that will be included in the output\n    page, which is automatically inserted on page render.\n    \"\"\"\n    def __init__(self, handler):\n        self.handler = handler\n        self.request = handler.request\n        self.ui = handler.ui\n        self.current_user = handler.current_user\n        self.locale = handler.locale\n\n    def render(self, *args, **kwargs):\n        \"\"\"Overridden in subclasses to return this module's output.\"\"\"\n        raise NotImplementedError()\n\n    def embedded_javascript(self):\n        \"\"\"Returns a JavaScript string that will be embedded in the page.\"\"\"\n        return None\n\n    def javascript_files(self):\n        \"\"\"Returns a list of JavaScript files required by this module.\"\"\"\n        return None\n\n    def embedded_css(self):\n        \"\"\"Returns a CSS string that will be embedded in the page.\"\"\"\n        return None\n\n    def css_files(self):\n        \"\"\"Returns a list of CSS files required by this module.\"\"\"\n        return None\n\n    def html_head(self):\n        \"\"\"Returns a CSS string that will be put in the <head/> element\"\"\"\n        return None\n\n    def html_body(self):\n        \"\"\"Returns an HTML string that will be put in the <body/> element\"\"\"\n        return None\n\n    def render_string(self, path, **kwargs):\n        \"\"\"Renders a template and returns it as a string.\"\"\"\n        return self.handler.render_string(path, **kwargs)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 2301,
                            "end_lineno": 2345,
                            "parent": null
                        }
                    ],
                    "added_entities": [
                        {
                            "file_name": "tornado/web.py",
                            "type": "method",
                            "name": "UIModule.current_user",
                            "content": "class UIModule(object):\n    \"\"\"A re-usable, modular UI unit on a page.\n\n    UI modules often execute additional queries, and they can include\n    additional CSS and JavaScript that will be included in the output\n    page, which is automatically inserted on page render.\n    \"\"\"\n    def __init__(self, handler):\n        self.handler = handler\n        self.request = handler.request\n        self.ui = handler.ui\n        self.locale = handler.locale\n\n    @property\n    def current_user(self):\n        return self.handler.current_user\n\n    def render(self, *args, **kwargs):\n        \"\"\"Overridden in subclasses to return this module's output.\"\"\"\n        raise NotImplementedError()\n\n    def embedded_javascript(self):\n        \"\"\"Returns a JavaScript string that will be embedded in the page.\"\"\"\n        return None\n\n    def javascript_files(self):\n        \"\"\"Returns a list of JavaScript files required by this module.\"\"\"\n        return None\n\n    def embedded_css(self):\n        \"\"\"Returns a CSS string that will be embedded in the page.\"\"\"\n        return None\n\n    def css_files(self):\n        \"\"\"Returns a list of CSS files required by this module.\"\"\"\n        return None\n\n    def html_head(self):\n        \"\"\"Returns a CSS string that will be put in the <head/> element\"\"\"\n        return None\n\n    def html_body(self):\n        \"\"\"Returns an HTML string that will be put in the <body/> element\"\"\"\n        return None\n\n    def render_string(self, path, **kwargs):\n        \"\"\"Renders a template and returns it as a string.\"\"\"\n        return self.handler.render_string(path, **kwargs)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 2315,
                            "end_lineno": 2316,
                            "parent": {
                                "file_name": "tornado/web.py",
                                "type": "class",
                                "name": "UIModule",
                                "content": "class UIModule(object):\n    \"\"\"A re-usable, modular UI unit on a page.\n\n    UI modules often execute additional queries, and they can include\n    additional CSS and JavaScript that will be included in the output\n    page, which is automatically inserted on page render.\n    \"\"\"\n    def __init__(self, handler):\n        self.handler = handler\n        self.request = handler.request\n        self.ui = handler.ui\n        self.locale = handler.locale\n\n    @property\n    def current_user(self):\n        return self.handler.current_user\n\n    def render(self, *args, **kwargs):\n        \"\"\"Overridden in subclasses to return this module's output.\"\"\"\n        raise NotImplementedError()\n\n    def embedded_javascript(self):\n        \"\"\"Returns a JavaScript string that will be embedded in the page.\"\"\"\n        return None\n\n    def javascript_files(self):\n        \"\"\"Returns a list of JavaScript files required by this module.\"\"\"\n        return None\n\n    def embedded_css(self):\n        \"\"\"Returns a CSS string that will be embedded in the page.\"\"\"\n        return None\n\n    def css_files(self):\n        \"\"\"Returns a list of CSS files required by this module.\"\"\"\n        return None\n\n    def html_head(self):\n        \"\"\"Returns a CSS string that will be put in the <head/> element\"\"\"\n        return None\n\n    def html_body(self):\n        \"\"\"Returns an HTML string that will be put in the <body/> element\"\"\"\n        return None\n\n    def render_string(self, path, **kwargs):\n        \"\"\"Renders a template and returns it as a string.\"\"\"\n        return self.handler.render_string(path, **kwargs)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 2301,
                                "end_lineno": 2348,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "e4e93e9b493028f5848b9d7929087a335d615cef^",
    "new_commit_hash": "e4e93e9b493028f5848b9d7929087a335d615cef",
    "commit_message": "Merge pull request #848 from SuprDewd/issue_820\n\nFixed laziness of current_user in UI modules, and added tests for current_user.",
    "commit_date": "2013-07-15T18:04:09-07:00",
    "metadata": {}
}
{
    "repo_name": "tornado",
    "new_commit_hash": "e4e93e9b493028f5848b9d7929087a335d615cef",
    "test_file_codes": [
        "from __future__ import absolute_import, division, print_function, with_statement\nfrom tornado import gen\nfrom tornado.escape import json_decode, utf8, to_unicode, recursive_unicode, native_str, to_basestring\nfrom tornado.httputil import format_timestamp\nfrom tornado.iostream import IOStream\nfrom tornado.log import app_log, gen_log\nfrom tornado.simple_httpclient import SimpleAsyncHTTPClient\nfrom tornado.template import DictLoader\nfrom tornado.testing import AsyncHTTPTestCase, ExpectLog\nfrom tornado.test.util import unittest\nfrom tornado.util import u, bytes_type, ObjectDict, unicode_type\nfrom tornado.web import RequestHandler, authenticated, Application, asynchronous, url, HTTPError, StaticFileHandler, _create_signature, create_signed_value, ErrorHandler, UIModule, MissingArgumentError\n\nimport binascii\nimport datetime\nimport email.utils\nimport logging\nimport os\nimport re\nimport socket\nimport sys\n\nwsgi_safe_tests = []\n\nrelpath = lambda *a: os.path.join(os.path.dirname(__file__), *a)\n\n\ndef wsgi_safe(cls):\n    wsgi_safe_tests.append(cls)\n    return cls\n\n\nclass WebTestCase(AsyncHTTPTestCase):\n    \"\"\"Base class for web tests that also supports WSGI mode.\n\n    Override get_handlers and get_app_kwargs instead of get_app.\n    Append to wsgi_safe to have it run in wsgi_test as well.\n    \"\"\"\n    def get_app(self):\n        self.app = Application(self.get_handlers(), **self.get_app_kwargs())\n        return self.app\n\n    def get_handlers(self):\n        raise NotImplementedError()\n\n    def get_app_kwargs(self):\n        return {}\n\n\nclass SimpleHandlerTestCase(WebTestCase):\n    \"\"\"Simplified base class for tests that work with a single handler class.\n\n    To use, define a nested class named ``Handler``.\n    \"\"\"\n    def get_handlers(self):\n        return [('/', self.Handler)]\n\n\nclass CookieTestRequestHandler(RequestHandler):\n    # stub out enough methods to make the secure_cookie functions work\n    def __init__(self):\n        # don't call super.__init__\n        self._cookies = {}\n        self.application = ObjectDict(settings=dict(cookie_secret='0123456789'))\n\n    def get_cookie(self, name):\n        return self._cookies.get(name)\n\n    def set_cookie(self, name, value, expires_days=None):\n        self._cookies[name] = value\n\n\nclass SecureCookieTest(unittest.TestCase):\n    def test_round_trip(self):\n        handler = CookieTestRequestHandler()\n        handler.set_secure_cookie('foo', b'bar')\n        self.assertEqual(handler.get_secure_cookie('foo'), b'bar')\n\n    def test_cookie_tampering_future_timestamp(self):\n        handler = CookieTestRequestHandler()\n        # this string base64-encodes to '12345678'\n        handler.set_secure_cookie('foo', binascii.a2b_hex(b'd76df8e7aefc'))\n        cookie = handler._cookies['foo']\n        match = re.match(br'12345678\\|([0-9]+)\\|([0-9a-f]+)', cookie)\n        self.assertTrue(match)\n        timestamp = match.group(1)\n        sig = match.group(2)\n        self.assertEqual(\n            _create_signature(handler.application.settings[\"cookie_secret\"],\n                              'foo', '12345678', timestamp),\n            sig)\n        # shifting digits from payload to timestamp doesn't alter signature\n        # (this is not desirable behavior, just confirming that that's how it\n        # works)\n        self.assertEqual(\n            _create_signature(handler.application.settings[\"cookie_secret\"],\n                              'foo', '1234', b'5678' + timestamp),\n            sig)\n        # tamper with the cookie\n        handler._cookies['foo'] = utf8('1234|5678%s|%s' % (\n            to_basestring(timestamp), to_basestring(sig)))\n        # it gets rejected\n        with ExpectLog(gen_log, \"Cookie timestamp in future\"):\n            self.assertTrue(handler.get_secure_cookie('foo') is None)\n\n    def test_arbitrary_bytes(self):\n        # Secure cookies accept arbitrary data (which is base64 encoded).\n        # Note that normal cookies accept only a subset of ascii.\n        handler = CookieTestRequestHandler()\n        handler.set_secure_cookie('foo', b'\\xe9')\n        self.assertEqual(handler.get_secure_cookie('foo'), b'\\xe9')\n\n\nclass CookieTest(WebTestCase):\n    def get_handlers(self):\n        class SetCookieHandler(RequestHandler):\n            def get(self):\n                # Try setting cookies with different argument types\n                # to ensure that everything gets encoded correctly\n                self.set_cookie(\"str\", \"asdf\")\n                self.set_cookie(\"unicode\", u(\"qwer\"))\n                self.set_cookie(\"bytes\", b\"zxcv\")\n\n        class GetCookieHandler(RequestHandler):\n            def get(self):\n                self.write(self.get_cookie(\"foo\", \"default\"))\n\n        class SetCookieDomainHandler(RequestHandler):\n            def get(self):\n                # unicode domain and path arguments shouldn't break things\n                # either (see bug #285)\n                self.set_cookie(\"unicode_args\", \"blah\", domain=u(\"foo.com\"),\n                                path=u(\"/foo\"))\n\n        class SetCookieSpecialCharHandler(RequestHandler):\n            def get(self):\n                self.set_cookie(\"equals\", \"a=b\")\n                self.set_cookie(\"semicolon\", \"a;b\")\n                self.set_cookie(\"quote\", 'a\"b')\n\n        class SetCookieOverwriteHandler(RequestHandler):\n            def get(self):\n                self.set_cookie(\"a\", \"b\", domain=\"example.com\")\n                self.set_cookie(\"c\", \"d\", domain=\"example.com\")\n                # A second call with the same name clobbers the first.\n                # Attributes from the first call are not carried over.\n                self.set_cookie(\"a\", \"e\")\n\n        return [(\"/set\", SetCookieHandler),\n                (\"/get\", GetCookieHandler),\n                (\"/set_domain\", SetCookieDomainHandler),\n                (\"/special_char\", SetCookieSpecialCharHandler),\n                (\"/set_overwrite\", SetCookieOverwriteHandler),\n                ]\n\n    def test_set_cookie(self):\n        response = self.fetch(\"/set\")\n        self.assertEqual(sorted(response.headers.get_list(\"Set-Cookie\")),\n                         [\"bytes=zxcv; Path=/\",\n                          \"str=asdf; Path=/\",\n                          \"unicode=qwer; Path=/\",\n                          ])\n\n    def test_get_cookie(self):\n        response = self.fetch(\"/get\", headers={\"Cookie\": \"foo=bar\"})\n        self.assertEqual(response.body, b\"bar\")\n\n        response = self.fetch(\"/get\", headers={\"Cookie\": 'foo=\"bar\"'})\n        self.assertEqual(response.body, b\"bar\")\n\n        response = self.fetch(\"/get\", headers={\"Cookie\": \"/=exception;\"})\n        self.assertEqual(response.body, b\"default\")\n\n    def test_set_cookie_domain(self):\n        response = self.fetch(\"/set_domain\")\n        self.assertEqual(response.headers.get_list(\"Set-Cookie\"),\n                         [\"unicode_args=blah; Domain=foo.com; Path=/foo\"])\n\n    def test_cookie_special_char(self):\n        response = self.fetch(\"/special_char\")\n        headers = sorted(response.headers.get_list(\"Set-Cookie\"))\n        self.assertEqual(len(headers), 3)\n        self.assertEqual(headers[0], 'equals=\"a=b\"; Path=/')\n        self.assertEqual(headers[1], 'quote=\"a\\\\\"b\"; Path=/')\n        # python 2.7 octal-escapes the semicolon; older versions leave it alone\n        self.assertTrue(headers[2] in ('semicolon=\"a;b\"; Path=/',\n                                       'semicolon=\"a\\\\073b\"; Path=/'),\n                        headers[2])\n\n        data = [('foo=a=b', 'a=b'),\n                ('foo=\"a=b\"', 'a=b'),\n                ('foo=\"a;b\"', 'a;b'),\n                # ('foo=a\\\\073b', 'a;b'),  # even encoded, \";\" is a delimiter\n                ('foo=\"a\\\\073b\"', 'a;b'),\n                ('foo=\"a\\\\\"b\"', 'a\"b'),\n                ]\n        for header, expected in data:\n            logging.debug(\"trying %r\", header)\n            response = self.fetch(\"/get\", headers={\"Cookie\": header})\n            self.assertEqual(response.body, utf8(expected))\n\n    def test_set_cookie_overwrite(self):\n        response = self.fetch(\"/set_overwrite\")\n        headers = response.headers.get_list(\"Set-Cookie\")\n        self.assertEqual(sorted(headers),\n                         [\"a=e; Path=/\", \"c=d; Domain=example.com; Path=/\"])\n\n\nclass AuthRedirectRequestHandler(RequestHandler):\n    def initialize(self, login_url):\n        self.login_url = login_url\n\n    def get_login_url(self):\n        return self.login_url\n\n    @authenticated\n    def get(self):\n        # we'll never actually get here because the test doesn't follow redirects\n        self.send_error(500)\n\n\nclass AuthRedirectTest(WebTestCase):\n    def get_handlers(self):\n        return [('/relative', AuthRedirectRequestHandler,\n                 dict(login_url='/login')),\n                ('/absolute', AuthRedirectRequestHandler,\n                 dict(login_url='http://example.com/login'))]\n\n    def test_relative_auth_redirect(self):\n        self.http_client.fetch(self.get_url('/relative'), self.stop,\n                               follow_redirects=False)\n        response = self.wait()\n        self.assertEqual(response.code, 302)\n        self.assertEqual(response.headers['Location'], '/login?next=%2Frelative')\n\n    def test_absolute_auth_redirect(self):\n        self.http_client.fetch(self.get_url('/absolute'), self.stop,\n                               follow_redirects=False)\n        response = self.wait()\n        self.assertEqual(response.code, 302)\n        self.assertTrue(re.match(\n            'http://example.com/login\\?next=http%3A%2F%2Flocalhost%3A[0-9]+%2Fabsolute',\n            response.headers['Location']), response.headers['Location'])\n\n\nclass ConnectionCloseHandler(RequestHandler):\n    def initialize(self, test):\n        self.test = test\n\n    @asynchronous\n    def get(self):\n        self.test.on_handler_waiting()\n\n    def on_connection_close(self):\n        self.test.on_connection_close()\n\n\nclass ConnectionCloseTest(WebTestCase):\n    def get_handlers(self):\n        return [('/', ConnectionCloseHandler, dict(test=self))]\n\n    def test_connection_close(self):\n        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)\n        s.connect((\"localhost\", self.get_http_port()))\n        self.stream = IOStream(s, io_loop=self.io_loop)\n        self.stream.write(b\"GET / HTTP/1.0\\r\\n\\r\\n\")\n        self.wait()\n\n    def on_handler_waiting(self):\n        logging.debug('handler waiting')\n        self.stream.close()\n\n    def on_connection_close(self):\n        logging.debug('connection closed')\n        self.stop()\n\n\nclass EchoHandler(RequestHandler):\n    def get(self, *path_args):\n        # Type checks: web.py interfaces convert argument values to\n        # unicode strings (by default, but see also decode_argument).\n        # In httpserver.py (i.e. self.request.arguments), they're left\n        # as bytes.  Keys are always native strings.\n        for key in self.request.arguments:\n            if type(key) != str:\n                raise Exception(\"incorrect type for key: %r\" % type(key))\n            for value in self.request.arguments[key]:\n                if type(value) != bytes_type:\n                    raise Exception(\"incorrect type for value: %r\" %\n                                    type(value))\n            for value in self.get_arguments(key):\n                if type(value) != unicode_type:\n                    raise Exception(\"incorrect type for value: %r\" %\n                                    type(value))\n        for arg in path_args:\n            if type(arg) != unicode_type:\n                raise Exception(\"incorrect type for path arg: %r\" % type(arg))\n        self.write(dict(path=self.request.path,\n                        path_args=path_args,\n                        args=recursive_unicode(self.request.arguments)))\n\n\nclass RequestEncodingTest(WebTestCase):\n    def get_handlers(self):\n        return [(\"/group/(.*)\", EchoHandler),\n                (\"/slashes/([^/]*)/([^/]*)\", EchoHandler),\n                ]\n\n    def fetch_json(self, path):\n        return json_decode(self.fetch(path).body)\n\n    def test_group_question_mark(self):\n        # Ensure that url-encoded question marks are handled properly\n        self.assertEqual(self.fetch_json('/group/%3F'),\n                         dict(path='/group/%3F', path_args=['?'], args={}))\n        self.assertEqual(self.fetch_json('/group/%3F?%3F=%3F'),\n                         dict(path='/group/%3F', path_args=['?'], args={'?': ['?']}))\n\n    def test_group_encoding(self):\n        # Path components and query arguments should be decoded the same way\n        self.assertEqual(self.fetch_json('/group/%C3%A9?arg=%C3%A9'),\n                         {u(\"path\"): u(\"/group/%C3%A9\"),\n                          u(\"path_args\"): [u(\"\\u00e9\")],\n                          u(\"args\"): {u(\"arg\"): [u(\"\\u00e9\")]}})\n\n    def test_slashes(self):\n        # Slashes may be escaped to appear as a single \"directory\" in the path,\n        # but they are then unescaped when passed to the get() method.\n        self.assertEqual(self.fetch_json('/slashes/foo/bar'),\n                         dict(path=\"/slashes/foo/bar\",\n                              path_args=[\"foo\", \"bar\"],\n                              args={}))\n        self.assertEqual(self.fetch_json('/slashes/a%2Fb/c%2Fd'),\n                         dict(path=\"/slashes/a%2Fb/c%2Fd\",\n                              path_args=[\"a/b\", \"c/d\"],\n                              args={}))\n\n\nclass TypeCheckHandler(RequestHandler):\n    def prepare(self):\n        self.errors = {}\n\n        self.check_type('status', self.get_status(), int)\n\n        # get_argument is an exception from the general rule of using\n        # type str for non-body data mainly for historical reasons.\n        self.check_type('argument', self.get_argument('foo'), unicode_type)\n        self.check_type('cookie_key', list(self.cookies.keys())[0], str)\n        self.check_type('cookie_value', list(self.cookies.values())[0].value, str)\n\n        # Secure cookies return bytes because they can contain arbitrary\n        # data, but regular cookies are native strings.\n        if list(self.cookies.keys()) != ['asdf']:\n            raise Exception(\"unexpected values for cookie keys: %r\" %\n                            self.cookies.keys())\n        self.check_type('get_secure_cookie', self.get_secure_cookie('asdf'), bytes_type)\n        self.check_type('get_cookie', self.get_cookie('asdf'), str)\n\n        self.check_type('xsrf_token', self.xsrf_token, bytes_type)\n        self.check_type('xsrf_form_html', self.xsrf_form_html(), str)\n\n        self.check_type('reverse_url', self.reverse_url('typecheck', 'foo'), str)\n\n        self.check_type('request_summary', self._request_summary(), str)\n\n    def get(self, path_component):\n        # path_component uses type unicode instead of str for consistency\n        # with get_argument()\n        self.check_type('path_component', path_component, unicode_type)\n        self.write(self.errors)\n\n    def post(self, path_component):\n        self.check_type('path_component', path_component, unicode_type)\n        self.write(self.errors)\n\n    def check_type(self, name, obj, expected_type):\n        actual_type = type(obj)\n        if expected_type != actual_type:\n            self.errors[name] = \"expected %s, got %s\" % (expected_type,\n                                                         actual_type)\n\n\nclass DecodeArgHandler(RequestHandler):\n    def decode_argument(self, value, name=None):\n        if type(value) != bytes_type:\n            raise Exception(\"unexpected type for value: %r\" % type(value))\n        # use self.request.arguments directly to avoid recursion\n        if 'encoding' in self.request.arguments:\n            return value.decode(to_unicode(self.request.arguments['encoding'][0]))\n        else:\n            return value\n\n    def get(self, arg):\n        def describe(s):\n            if type(s) == bytes_type:\n                return [\"bytes\", native_str(binascii.b2a_hex(s))]\n            elif type(s) == unicode_type:\n                return [\"unicode\", s]\n            raise Exception(\"unknown type\")\n        self.write({'path': describe(arg),\n                    'query': describe(self.get_argument(\"foo\")),\n                    })\n\n\nclass LinkifyHandler(RequestHandler):\n    def get(self):\n        self.render(\"linkify.html\", message=\"http://example.com\")\n\n\nclass UIModuleResourceHandler(RequestHandler):\n    def get(self):\n        self.render(\"page.html\", entries=[1, 2])\n\n\nclass OptionalPathHandler(RequestHandler):\n    def get(self, path):\n        self.write({\"path\": path})\n\n\nclass FlowControlHandler(RequestHandler):\n    # These writes are too small to demonstrate real flow control,\n    # but at least it shows that the callbacks get run.\n    @asynchronous\n    def get(self):\n        self.write(\"1\")\n        self.flush(callback=self.step2)\n\n    def step2(self):\n        self.write(\"2\")\n        self.flush(callback=self.step3)\n\n    def step3(self):\n        self.write(\"3\")\n        self.finish()\n\n\nclass MultiHeaderHandler(RequestHandler):\n    def get(self):\n        self.set_header(\"x-overwrite\", \"1\")\n        self.set_header(\"X-Overwrite\", 2)\n        self.add_header(\"x-multi\", 3)\n        self.add_header(\"X-Multi\", \"4\")\n\n\nclass RedirectHandler(RequestHandler):\n    def get(self):\n        if self.get_argument('permanent', None) is not None:\n            self.redirect('/', permanent=int(self.get_argument('permanent')))\n        elif self.get_argument('status', None) is not None:\n            self.redirect('/', status=int(self.get_argument('status')))\n        else:\n            raise Exception(\"didn't get permanent or status arguments\")\n\n\nclass EmptyFlushCallbackHandler(RequestHandler):\n    @gen.engine\n    @asynchronous\n    def get(self):\n        # Ensure that the flush callback is run whether or not there\n        # was any output.\n        yield gen.Task(self.flush)  # \"empty\" flush, but writes headers\n        yield gen.Task(self.flush)  # empty flush\n        self.write(\"o\")\n        yield gen.Task(self.flush)  # flushes the \"o\"\n        yield gen.Task(self.flush)  # empty flush\n        self.finish(\"k\")\n\n\nclass HeaderInjectionHandler(RequestHandler):\n    def get(self):\n        try:\n            self.set_header(\"X-Foo\", \"foo\\r\\nX-Bar: baz\")\n            raise Exception(\"Didn't get expected exception\")\n        except ValueError as e:\n            if \"Unsafe header value\" in str(e):\n                self.finish(b\"ok\")\n            else:\n                raise\n\n\nclass GetArgumentHandler(RequestHandler):\n    def get(self):\n        self.write(self.get_argument(\"foo\", \"default\"))\n\n\n# This test is shared with wsgi_test.py\n@wsgi_safe\nclass WSGISafeWebTest(WebTestCase):\n    COOKIE_SECRET = \"WebTest.COOKIE_SECRET\"\n\n    def get_app_kwargs(self):\n        loader = DictLoader({\n            \"linkify.html\": \"{% module linkify(message) %}\",\n            \"page.html\": \"\"\"\\\n<html><head></head><body>\n{% for e in entries %}\n{% module Template(\"entry.html\", entry=e) %}\n{% end %}\n</body></html>\"\"\",\n            \"entry.html\": \"\"\"\\\n{{ set_resources(embedded_css=\".entry { margin-bottom: 1em; }\", embedded_javascript=\"js_embed()\", css_files=[\"/base.css\", \"/foo.css\"], javascript_files=\"/common.js\", html_head=\"<meta>\", html_body='<script src=\"/analytics.js\"/>') }}\n<div class=\"entry\">...</div>\"\"\",\n        })\n        return dict(template_loader=loader,\n                    autoescape=\"xhtml_escape\",\n                    cookie_secret=self.COOKIE_SECRET)\n\n    def tearDown(self):\n        super(WSGISafeWebTest, self).tearDown()\n        RequestHandler._template_loaders.clear()\n\n    def get_handlers(self):\n        urls = [\n            url(\"/typecheck/(.*)\", TypeCheckHandler, name='typecheck'),\n            url(\"/decode_arg/(.*)\", DecodeArgHandler, name='decode_arg'),\n            url(\"/decode_arg_kw/(?P<arg>.*)\", DecodeArgHandler),\n            url(\"/linkify\", LinkifyHandler),\n            url(\"/uimodule_resources\", UIModuleResourceHandler),\n            url(\"/optional_path/(.+)?\", OptionalPathHandler),\n            url(\"/multi_header\", MultiHeaderHandler),\n            url(\"/redirect\", RedirectHandler),\n            url(\"/header_injection\", HeaderInjectionHandler),\n            url(\"/get_argument\", GetArgumentHandler),\n        ]\n        return urls\n\n    def fetch_json(self, *args, **kwargs):\n        response = self.fetch(*args, **kwargs)\n        response.rethrow()\n        return json_decode(response.body)\n\n    def test_types(self):\n        cookie_value = to_unicode(create_signed_value(self.COOKIE_SECRET,\n                                                      \"asdf\", \"qwer\"))\n        response = self.fetch(\"/typecheck/asdf?foo=bar\",\n                              headers={\"Cookie\": \"asdf=\" + cookie_value})\n        data = json_decode(response.body)\n        self.assertEqual(data, {})\n\n        response = self.fetch(\"/typecheck/asdf?foo=bar\", method=\"POST\",\n                              headers={\"Cookie\": \"asdf=\" + cookie_value},\n                              body=\"foo=bar\")\n\n    def test_decode_argument(self):\n        # These urls all decode to the same thing\n        urls = [\"/decode_arg/%C3%A9?foo=%C3%A9&encoding=utf-8\",\n                \"/decode_arg/%E9?foo=%E9&encoding=latin1\",\n                \"/decode_arg_kw/%E9?foo=%E9&encoding=latin1\",\n                ]\n        for url in urls:\n            response = self.fetch(url)\n            response.rethrow()\n            data = json_decode(response.body)\n            self.assertEqual(data, {u('path'): [u('unicode'), u('\\u00e9')],\n                                    u('query'): [u('unicode'), u('\\u00e9')],\n                                    })\n\n        response = self.fetch(\"/decode_arg/%C3%A9?foo=%C3%A9\")\n        response.rethrow()\n        data = json_decode(response.body)\n        self.assertEqual(data, {u('path'): [u('bytes'), u('c3a9')],\n                                u('query'): [u('bytes'), u('c3a9')],\n                                })\n\n    def test_decode_argument_plus(self):\n        # These urls are all equivalent.\n        urls = [\"/decode_arg/1%20%2B%201?foo=1%20%2B%201&encoding=utf-8\",\n                \"/decode_arg/1%20+%201?foo=1+%2B+1&encoding=utf-8\"]\n        for url in urls:\n            response = self.fetch(url)\n            response.rethrow()\n            data = json_decode(response.body)\n            self.assertEqual(data, {u('path'): [u('unicode'), u('1 + 1')],\n                                    u('query'): [u('unicode'), u('1 + 1')],\n                                    })\n\n    def test_reverse_url(self):\n        self.assertEqual(self.app.reverse_url('decode_arg', 'foo'),\n                         '/decode_arg/foo')\n        self.assertEqual(self.app.reverse_url('decode_arg', 42),\n                         '/decode_arg/42')\n        self.assertEqual(self.app.reverse_url('decode_arg', b'\\xe9'),\n                         '/decode_arg/%E9')\n        self.assertEqual(self.app.reverse_url('decode_arg', u('\\u00e9')),\n                         '/decode_arg/%C3%A9')\n        self.assertEqual(self.app.reverse_url('decode_arg', '1 + 1'),\n                         '/decode_arg/1%20%2B%201')\n\n    def test_uimodule_unescaped(self):\n        response = self.fetch(\"/linkify\")\n        self.assertEqual(response.body,\n                         b\"<a href=\\\"http://example.com\\\">http://example.com</a>\")\n\n    def test_uimodule_resources(self):\n        response = self.fetch(\"/uimodule_resources\")\n        self.assertEqual(response.body, b\"\"\"\\\n<html><head><link href=\"/base.css\" type=\"text/css\" rel=\"stylesheet\"/><link href=\"/foo.css\" type=\"text/css\" rel=\"stylesheet\"/>\n<style type=\"text/css\">\n.entry { margin-bottom: 1em; }\n</style>\n<meta>\n</head><body>\n\n\n<div class=\"entry\">...</div>\n\n\n<div class=\"entry\">...</div>\n\n<script src=\"/common.js\" type=\"text/javascript\"></script>\n<script type=\"text/javascript\">\n//<![CDATA[\njs_embed()\n//]]>\n</script>\n<script src=\"/analytics.js\"/>\n</body></html>\"\"\")\n\n    def test_optional_path(self):\n        self.assertEqual(self.fetch_json(\"/optional_path/foo\"),\n                         {u(\"path\"): u(\"foo\")})\n        self.assertEqual(self.fetch_json(\"/optional_path/\"),\n                         {u(\"path\"): None})\n\n    def test_multi_header(self):\n        response = self.fetch(\"/multi_header\")\n        self.assertEqual(response.headers[\"x-overwrite\"], \"2\")\n        self.assertEqual(response.headers.get_list(\"x-multi\"), [\"3\", \"4\"])\n\n    def test_redirect(self):\n        response = self.fetch(\"/redirect?permanent=1\", follow_redirects=False)\n        self.assertEqual(response.code, 301)\n        response = self.fetch(\"/redirect?permanent=0\", follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        response = self.fetch(\"/redirect?status=307\", follow_redirects=False)\n        self.assertEqual(response.code, 307)\n\n    def test_header_injection(self):\n        response = self.fetch(\"/header_injection\")\n        self.assertEqual(response.body, b\"ok\")\n\n    def test_get_argument(self):\n        response = self.fetch(\"/get_argument?foo=bar\")\n        self.assertEqual(response.body, b\"bar\")\n        response = self.fetch(\"/get_argument?foo=\")\n        self.assertEqual(response.body, b\"\")\n        response = self.fetch(\"/get_argument\")\n        self.assertEqual(response.body, b\"default\")\n\n    def test_no_gzip(self):\n        response = self.fetch('/get_argument')\n        self.assertNotIn('Accept-Encoding', response.headers.get('Vary', ''))\n        self.assertNotIn('gzip', response.headers.get('Content-Encoding', ''))\n\n\nclass NonWSGIWebTests(WebTestCase):\n    def get_handlers(self):\n        return [(\"/flow_control\", FlowControlHandler),\n                (\"/empty_flush\", EmptyFlushCallbackHandler),\n                ]\n\n    def test_flow_control(self):\n        self.assertEqual(self.fetch(\"/flow_control\").body, b\"123\")\n\n    def test_empty_flush(self):\n        response = self.fetch(\"/empty_flush\")\n        self.assertEqual(response.body, b\"ok\")\n\n\n@wsgi_safe\nclass ErrorResponseTest(WebTestCase):\n    def get_handlers(self):\n        class DefaultHandler(RequestHandler):\n            def get(self):\n                if self.get_argument(\"status\", None):\n                    raise HTTPError(int(self.get_argument(\"status\")))\n                1 / 0\n\n        class WriteErrorHandler(RequestHandler):\n            def get(self):\n                if self.get_argument(\"status\", None):\n                    self.send_error(int(self.get_argument(\"status\")))\n                else:\n                    1 / 0\n\n            def write_error(self, status_code, **kwargs):\n                self.set_header(\"Content-Type\", \"text/plain\")\n                if \"exc_info\" in kwargs:\n                    self.write(\"Exception: %s\" % kwargs[\"exc_info\"][0].__name__)\n                else:\n                    self.write(\"Status: %d\" % status_code)\n\n        class GetErrorHtmlHandler(RequestHandler):\n            def get(self):\n                if self.get_argument(\"status\", None):\n                    self.send_error(int(self.get_argument(\"status\")))\n                else:\n                    1 / 0\n\n            def get_error_html(self, status_code, **kwargs):\n                self.set_header(\"Content-Type\", \"text/plain\")\n                if \"exception\" in kwargs:\n                    self.write(\"Exception: %s\" % sys.exc_info()[0].__name__)\n                else:\n                    self.write(\"Status: %d\" % status_code)\n\n        class FailedWriteErrorHandler(RequestHandler):\n            def get(self):\n                1 / 0\n\n            def write_error(self, status_code, **kwargs):\n                raise Exception(\"exception in write_error\")\n\n        return [url(\"/default\", DefaultHandler),\n                url(\"/write_error\", WriteErrorHandler),\n                url(\"/get_error_html\", GetErrorHtmlHandler),\n                url(\"/failed_write_error\", FailedWriteErrorHandler),\n                ]\n\n    def test_default(self):\n        with ExpectLog(app_log, \"Uncaught exception\"):\n            response = self.fetch(\"/default\")\n            self.assertEqual(response.code, 500)\n            self.assertTrue(b\"500: Internal Server Error\" in response.body)\n\n            response = self.fetch(\"/default?status=503\")\n            self.assertEqual(response.code, 503)\n            self.assertTrue(b\"503: Service Unavailable\" in response.body)\n\n    def test_write_error(self):\n        with ExpectLog(app_log, \"Uncaught exception\"):\n            response = self.fetch(\"/write_error\")\n            self.assertEqual(response.code, 500)\n            self.assertEqual(b\"Exception: ZeroDivisionError\", response.body)\n\n            response = self.fetch(\"/write_error?status=503\")\n            self.assertEqual(response.code, 503)\n            self.assertEqual(b\"Status: 503\", response.body)\n\n    def test_get_error_html(self):\n        with ExpectLog(app_log, \"Uncaught exception\"):\n            response = self.fetch(\"/get_error_html\")\n            self.assertEqual(response.code, 500)\n            self.assertEqual(b\"Exception: ZeroDivisionError\", response.body)\n\n            response = self.fetch(\"/get_error_html?status=503\")\n            self.assertEqual(response.code, 503)\n            self.assertEqual(b\"Status: 503\", response.body)\n\n    def test_failed_write_error(self):\n        with ExpectLog(app_log, \"Uncaught exception\"):\n            response = self.fetch(\"/failed_write_error\")\n            self.assertEqual(response.code, 500)\n            self.assertEqual(b\"\", response.body)\n\n\n@wsgi_safe\nclass StaticFileTest(WebTestCase):\n    # The expected MD5 hash of robots.txt, used in tests that call\n    # StaticFileHandler.get_version\n    robots_txt_hash = b\"f71d20196d4caf35b6a670db8c70b03d\"\n    static_dir = os.path.join(os.path.dirname(__file__), 'static')\n\n    def get_handlers(self):\n        class StaticUrlHandler(RequestHandler):\n            def get(self, path):\n                with_v = int(self.get_argument('include_version', 1))\n                self.write(self.static_url(path, include_version=with_v))\n\n        class AbsoluteStaticUrlHandler(StaticUrlHandler):\n            include_host = True\n\n        class OverrideStaticUrlHandler(RequestHandler):\n            def get(self, path):\n                do_include = bool(self.get_argument(\"include_host\"))\n                self.include_host = not do_include\n\n                regular_url = self.static_url(path)\n                override_url = self.static_url(path, include_host=do_include)\n                if override_url == regular_url:\n                    return self.write(str(False))\n\n                protocol = self.request.protocol + \"://\"\n                protocol_length = len(protocol)\n                check_regular = regular_url.find(protocol, 0, protocol_length)\n                check_override = override_url.find(protocol, 0, protocol_length)\n\n                if do_include:\n                    result = (check_override == 0 and check_regular == -1)\n                else:\n                    result = (check_override == -1 and check_regular == 0)\n                self.write(str(result))\n\n        return [('/static_url/(.*)', StaticUrlHandler),\n                ('/abs_static_url/(.*)', AbsoluteStaticUrlHandler),\n                ('/override_static_url/(.*)', OverrideStaticUrlHandler)]\n\n    def get_app_kwargs(self):\n        return dict(static_path=relpath('static'))\n\n    def test_static_files(self):\n        response = self.fetch('/robots.txt')\n        self.assertTrue(b\"Disallow: /\" in response.body)\n\n        response = self.fetch('/static/robots.txt')\n        self.assertTrue(b\"Disallow: /\" in response.body)\n\n    def test_static_url(self):\n        response = self.fetch(\"/static_url/robots.txt\")\n        self.assertEqual(response.body,\n                         b\"/static/robots.txt?v=\" + self.robots_txt_hash)\n\n    def test_absolute_static_url(self):\n        response = self.fetch(\"/abs_static_url/robots.txt\")\n        self.assertEqual(response.body, (\n            utf8(self.get_url(\"/\")) +\n            b\"static/robots.txt?v=\" +\n            self.robots_txt_hash\n        ))\n\n    def test_relative_version_exclusion(self):\n        response = self.fetch(\"/static_url/robots.txt?include_version=0\")\n        self.assertEqual(response.body, b\"/static/robots.txt\")\n\n    def test_absolute_version_exclusion(self):\n        response = self.fetch(\"/abs_static_url/robots.txt?include_version=0\")\n        self.assertEqual(response.body,\n                         utf8(self.get_url(\"/\") + \"static/robots.txt\"))\n\n    def test_include_host_override(self):\n        self._trigger_include_host_check(False)\n        self._trigger_include_host_check(True)\n\n    def _trigger_include_host_check(self, include_host):\n        path = \"/override_static_url/robots.txt?include_host=%s\"\n        response = self.fetch(path % int(include_host))\n        self.assertEqual(response.body, utf8(str(True)))\n\n    def test_static_304_if_modified_since(self):\n        response1 = self.fetch(\"/static/robots.txt\")\n        response2 = self.fetch(\"/static/robots.txt\", headers={\n            'If-Modified-Since': response1.headers['Last-Modified']})\n        self.assertEqual(response2.code, 304)\n        self.assertTrue('Content-Length' not in response2.headers)\n        self.assertTrue('Last-Modified' not in response2.headers)\n\n    def test_static_304_if_none_match(self):\n        response1 = self.fetch(\"/static/robots.txt\")\n        response2 = self.fetch(\"/static/robots.txt\", headers={\n            'If-None-Match': response1.headers['Etag']})\n        self.assertEqual(response2.code, 304)\n\n    def test_static_if_modified_since_pre_epoch(self):\n        # On windows, the functions that work with time_t do not accept\n        # negative values, and at least one client (processing.js) seems\n        # to use if-modified-since 1/1/1960 as a cache-busting technique.\n        response = self.fetch(\"/static/robots.txt\", headers={\n            'If-Modified-Since': 'Fri, 01 Jan 1960 00:00:00 GMT'})\n        self.assertEqual(response.code, 200)\n\n    def test_static_if_modified_since_time_zone(self):\n        # Instead of the value from Last-Modified, make requests with times\n        # chosen just before and after the known modification time\n        # of the file to ensure that the right time zone is being used\n        # when parsing If-Modified-Since.\n        stat = os.stat(relpath('static/robots.txt'))\n\n        response = self.fetch('/static/robots.txt', headers={\n            'If-Modified-Since': format_timestamp(stat.st_mtime - 1)})\n        self.assertEqual(response.code, 200)\n        response = self.fetch('/static/robots.txt', headers={\n            'If-Modified-Since': format_timestamp(stat.st_mtime + 1)})\n        self.assertEqual(response.code, 304)\n\n    def test_static_etag(self):\n        response = self.fetch('/static/robots.txt')\n        self.assertEqual(utf8(response.headers.get(\"Etag\")),\n                         b'\"' + self.robots_txt_hash + b'\"')\n\n    def test_static_with_range(self):\n        response = self.fetch('/static/robots.txt', headers={\n            'Range': 'bytes=0-9'})\n        self.assertEqual(response.code, 206)\n        self.assertEqual(response.body, b\"User-agent\")\n        self.assertEqual(utf8(response.headers.get(\"Etag\")),\n                         b'\"' + self.robots_txt_hash + b'\"')\n        self.assertEqual(response.headers.get(\"Content-Length\"), \"10\")\n        self.assertEqual(response.headers.get(\"Content-Range\"),\n                         \"bytes 0-9/26\")\n\n    def test_static_with_range_full_file(self):\n        response = self.fetch('/static/robots.txt', headers={\n            'Range': 'bytes=0-'})\n        # Note: Chrome refuses to play audio if it gets an HTTP 206 in response\n        # to ``Range: bytes=0-`` :(\n        self.assertEqual(response.code, 200)\n        robots_file_path = os.path.join(self.static_dir, \"robots.txt\")\n        with open(robots_file_path) as f:\n            self.assertEqual(response.body, utf8(f.read()))\n        self.assertEqual(response.headers.get(\"Content-Length\"), \"26\")\n        self.assertEqual(response.headers.get(\"Content-Range\"), None)\n\n    def test_static_with_range_full_past_end(self):\n        response = self.fetch('/static/robots.txt', headers={\n            'Range': 'bytes=0-10000000'})\n        self.assertEqual(response.code, 200)\n        robots_file_path = os.path.join(self.static_dir, \"robots.txt\")\n        with open(robots_file_path) as f:\n            self.assertEqual(response.body, utf8(f.read()))\n        self.assertEqual(response.headers.get(\"Content-Length\"), \"26\")\n        self.assertEqual(response.headers.get(\"Content-Range\"), None)\n\n    def test_static_with_range_partial_past_end(self):\n        response = self.fetch('/static/robots.txt', headers={\n            'Range': 'bytes=1-10000000'})\n        self.assertEqual(response.code, 206)\n        robots_file_path = os.path.join(self.static_dir, \"robots.txt\")\n        with open(robots_file_path) as f:\n            self.assertEqual(response.body, utf8(f.read()[1:]))\n        self.assertEqual(response.headers.get(\"Content-Length\"), \"25\")\n        self.assertEqual(response.headers.get(\"Content-Range\"), \"bytes 1-25/26\")\n\n    def test_static_with_range_end_edge(self):\n        response = self.fetch('/static/robots.txt', headers={\n            'Range': 'bytes=22-'})\n        self.assertEqual(response.body, b\": /\\n\")\n        self.assertEqual(response.headers.get(\"Content-Length\"), \"4\")\n        self.assertEqual(response.headers.get(\"Content-Range\"),\n                         \"bytes 22-25/26\")\n\n    def test_static_with_range_neg_end(self):\n        response = self.fetch('/static/robots.txt', headers={\n            'Range': 'bytes=-4'})\n        self.assertEqual(response.body, b\": /\\n\")\n        self.assertEqual(response.headers.get(\"Content-Length\"), \"4\")\n        self.assertEqual(response.headers.get(\"Content-Range\"),\n                         \"bytes 22-25/26\")\n\n    def test_static_invalid_range(self):\n        response = self.fetch('/static/robots.txt', headers={\n            'Range': 'asdf'})\n        self.assertEqual(response.code, 200)\n\n    def test_static_unsatisfiable_range_zero_suffix(self):\n        response = self.fetch('/static/robots.txt', headers={\n            'Range': 'bytes=-0'})\n        self.assertEqual(response.headers.get(\"Content-Range\"),\n                         \"bytes */26\")\n        self.assertEqual(response.code, 416)\n\n    def test_static_unsatisfiable_range_invalid_start(self):\n        response = self.fetch('/static/robots.txt', headers={\n            'Range': 'bytes=26'})\n        self.assertEqual(response.code, 416)\n        self.assertEqual(response.headers.get(\"Content-Range\"),\n                         \"bytes */26\")\n\n    def test_static_head(self):\n        response = self.fetch('/static/robots.txt', method='HEAD')\n        self.assertEqual(response.code, 200)\n        # No body was returned, but we did get the right content length.\n        self.assertEqual(response.body, b'')\n        self.assertEqual(response.headers['Content-Length'], '26')\n        self.assertEqual(utf8(response.headers['Etag']),\n                         b'\"' + self.robots_txt_hash + b'\"')\n\n    def test_static_head_range(self):\n        response = self.fetch('/static/robots.txt', method='HEAD',\n                              headers={'Range': 'bytes=1-4'})\n        self.assertEqual(response.code, 206)\n        self.assertEqual(response.body, b'')\n        self.assertEqual(response.headers['Content-Length'], '4')\n        self.assertEqual(utf8(response.headers['Etag']),\n                         b'\"' + self.robots_txt_hash + b'\"')\n\n    def test_static_range_if_none_match(self):\n        response = self.fetch('/static/robots.txt', headers={\n            'Range': 'bytes=1-4',\n            'If-None-Match': b'\"' + self.robots_txt_hash + b'\"'})\n        self.assertEqual(response.code, 304)\n        self.assertEqual(response.body, b'')\n        self.assertTrue('Content-Length' not in response.headers)\n        self.assertEqual(utf8(response.headers['Etag']),\n                         b'\"' + self.robots_txt_hash + b'\"')\n\n    def test_static_404(self):\n        response = self.fetch('/static/blarg')\n        self.assertEqual(response.code, 404)\n\n\n@wsgi_safe\nclass StaticDefaultFilenameTest(WebTestCase):\n    def get_app_kwargs(self):\n        return dict(static_path=relpath('static'),\n                    static_handler_args=dict(default_filename='index.html'))\n\n    def get_handlers(self):\n        return []\n\n    def test_static_default_filename(self):\n        response = self.fetch('/static/dir/', follow_redirects=False)\n        self.assertEqual(response.code, 200)\n        self.assertEqual(b'this is the index\\n', response.body)\n\n    def test_static_default_redirect(self):\n        response = self.fetch('/static/dir', follow_redirects=False)\n        self.assertEqual(response.code, 301)\n        self.assertTrue(response.headers['Location'].endswith('/static/dir/'))\n\n\n@wsgi_safe\nclass StaticFileWithPathTest(WebTestCase):\n    def get_app_kwargs(self):\n        return dict(static_path=relpath('static'),\n                    static_handler_args=dict(default_filename='index.html'))\n\n    def get_handlers(self):\n        return [(\"/foo/(.*)\", StaticFileHandler, {\n            \"path\": relpath(\"templates/\"),\n        })]\n\n    def test_serve(self):\n        response = self.fetch(\"/foo/utf8.html\")\n        self.assertEqual(response.body, b\"H\\xc3\\xa9llo\\n\")\n\n\n@wsgi_safe\nclass CustomStaticFileTest(WebTestCase):\n    def get_handlers(self):\n        class MyStaticFileHandler(StaticFileHandler):\n            @classmethod\n            def make_static_url(cls, settings, path):\n                version_hash = cls.get_version(settings, path)\n                extension_index = path.rindex('.')\n                before_version = path[:extension_index]\n                after_version = path[(extension_index + 1):]\n                return '/static/%s.%s.%s' % (before_version, version_hash,\n                                             after_version)\n\n            def parse_url_path(self, url_path):\n                extension_index = url_path.rindex('.')\n                version_index = url_path.rindex('.', 0, extension_index)\n                return '%s%s' % (url_path[:version_index],\n                                 url_path[extension_index:])\n\n            @classmethod\n            def get_absolute_path(cls, settings, path):\n                return 'CustomStaticFileTest:' + path\n\n            def validate_absolute_path(self, root, absolute_path):\n                return absolute_path\n\n            @classmethod\n            def get_content(self, path, start=None, end=None):\n                assert start is None and end is None\n                if path == 'CustomStaticFileTest:foo.txt':\n                    return b'bar'\n                raise Exception(\"unexpected path %r\" % path)\n\n            def get_modified_time(self):\n                return None\n\n            @classmethod\n            def get_version(cls, settings, path):\n                return \"42\"\n\n        class StaticUrlHandler(RequestHandler):\n            def get(self, path):\n                self.write(self.static_url(path))\n\n        self.static_handler_class = MyStaticFileHandler\n\n        return [(\"/static_url/(.*)\", StaticUrlHandler)]\n\n    def get_app_kwargs(self):\n        return dict(static_path=\"dummy\",\n                    static_handler_class=self.static_handler_class)\n\n    def test_serve(self):\n        response = self.fetch(\"/static/foo.42.txt\")\n        self.assertEqual(response.body, b\"bar\")\n\n    def test_static_url(self):\n        with ExpectLog(gen_log, \"Could not open static file\", required=False):\n            response = self.fetch(\"/static_url/foo.txt\")\n            self.assertEqual(response.body, b\"/static/foo.42.txt\")\n\n\n@wsgi_safe\nclass HostMatchingTest(WebTestCase):\n    class Handler(RequestHandler):\n        def initialize(self, reply):\n            self.reply = reply\n\n        def get(self):\n            self.write(self.reply)\n\n    def get_handlers(self):\n        return [(\"/foo\", HostMatchingTest.Handler, {\"reply\": \"wildcard\"})]\n\n    def test_host_matching(self):\n        self.app.add_handlers(\"www.example.com\",\n                              [(\"/foo\", HostMatchingTest.Handler, {\"reply\": \"[0]\"})])\n        self.app.add_handlers(r\"www\\.example\\.com\",\n                              [(\"/bar\", HostMatchingTest.Handler, {\"reply\": \"[1]\"})])\n        self.app.add_handlers(\"www.example.com\",\n                              [(\"/baz\", HostMatchingTest.Handler, {\"reply\": \"[2]\"})])\n\n        response = self.fetch(\"/foo\")\n        self.assertEqual(response.body, b\"wildcard\")\n        response = self.fetch(\"/bar\")\n        self.assertEqual(response.code, 404)\n        response = self.fetch(\"/baz\")\n        self.assertEqual(response.code, 404)\n\n        response = self.fetch(\"/foo\", headers={'Host': 'www.example.com'})\n        self.assertEqual(response.body, b\"[0]\")\n        response = self.fetch(\"/bar\", headers={'Host': 'www.example.com'})\n        self.assertEqual(response.body, b\"[1]\")\n        response = self.fetch(\"/baz\", headers={'Host': 'www.example.com'})\n        self.assertEqual(response.body, b\"[2]\")\n\n\n@wsgi_safe\nclass NamedURLSpecGroupsTest(WebTestCase):\n    def get_handlers(self):\n        class EchoHandler(RequestHandler):\n            def get(self, path):\n                self.write(path)\n\n        return [(\"/str/(?P<path>.*)\", EchoHandler),\n                (u(\"/unicode/(?P<path>.*)\"), EchoHandler)]\n\n    def test_named_urlspec_groups(self):\n        response = self.fetch(\"/str/foo\")\n        self.assertEqual(response.body, b\"foo\")\n\n        response = self.fetch(\"/unicode/bar\")\n        self.assertEqual(response.body, b\"bar\")\n\n\n@wsgi_safe\nclass ClearHeaderTest(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        def get(self):\n            self.set_header(\"h1\", \"foo\")\n            self.set_header(\"h2\", \"bar\")\n            self.clear_header(\"h1\")\n            self.clear_header(\"nonexistent\")\n\n    def test_clear_header(self):\n        response = self.fetch(\"/\")\n        self.assertTrue(\"h1\" not in response.headers)\n        self.assertEqual(response.headers[\"h2\"], \"bar\")\n\n\n@wsgi_safe\nclass Header304Test(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        def get(self):\n            self.set_header(\"Content-Language\", \"en_US\")\n            self.write(\"hello\")\n\n    def test_304_headers(self):\n        response1 = self.fetch('/')\n        self.assertEqual(response1.headers[\"Content-Length\"], \"5\")\n        self.assertEqual(response1.headers[\"Content-Language\"], \"en_US\")\n\n        response2 = self.fetch('/', headers={\n            'If-None-Match': response1.headers[\"Etag\"]})\n        self.assertEqual(response2.code, 304)\n        self.assertTrue(\"Content-Length\" not in response2.headers)\n        self.assertTrue(\"Content-Language\" not in response2.headers)\n        # Not an entity header, but should not be added to 304s by chunking\n        self.assertTrue(\"Transfer-Encoding\" not in response2.headers)\n\n\n@wsgi_safe\nclass StatusReasonTest(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        def get(self):\n            reason = self.request.arguments.get('reason', [])\n            self.set_status(int(self.get_argument('code')),\n                            reason=reason[0] if reason else None)\n\n    def get_http_client(self):\n        # simple_httpclient only: curl doesn't expose the reason string\n        return SimpleAsyncHTTPClient(io_loop=self.io_loop)\n\n    def test_status(self):\n        response = self.fetch(\"/?code=304\")\n        self.assertEqual(response.code, 304)\n        self.assertEqual(response.reason, \"Not Modified\")\n        response = self.fetch(\"/?code=304&reason=Foo\")\n        self.assertEqual(response.code, 304)\n        self.assertEqual(response.reason, \"Foo\")\n        response = self.fetch(\"/?code=682&reason=Bar\")\n        self.assertEqual(response.code, 682)\n        self.assertEqual(response.reason, \"Bar\")\n        with ExpectLog(app_log, 'Uncaught exception'):\n            response = self.fetch(\"/?code=682\")\n        self.assertEqual(response.code, 500)\n\n\n@wsgi_safe\nclass DateHeaderTest(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        def get(self):\n            self.write(\"hello\")\n\n    def test_date_header(self):\n        response = self.fetch('/')\n        header_date = datetime.datetime(\n            *email.utils.parsedate(response.headers['Date'])[:6])\n        self.assertTrue(header_date - datetime.datetime.utcnow() <\n                        datetime.timedelta(seconds=2))\n\n\n@wsgi_safe\nclass RaiseWithReasonTest(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        def get(self):\n            raise HTTPError(682, reason=\"Foo\")\n\n    def get_http_client(self):\n        # simple_httpclient only: curl doesn't expose the reason string\n        return SimpleAsyncHTTPClient(io_loop=self.io_loop)\n\n    def test_raise_with_reason(self):\n        response = self.fetch(\"/\")\n        self.assertEqual(response.code, 682)\n        self.assertEqual(response.reason, \"Foo\")\n        self.assertIn(b'682: Foo', response.body)\n\n    def test_httperror_str(self):\n        self.assertEqual(str(HTTPError(682, reason=\"Foo\")), \"HTTP 682: Foo\")\n\n\n@wsgi_safe\nclass ErrorHandlerXSRFTest(WebTestCase):\n    def get_handlers(self):\n        # note that if the handlers list is empty we get the default_host\n        # redirect fallback instead of a 404, so test with both an\n        # explicitly defined error handler and an implicit 404.\n        return [('/error', ErrorHandler, dict(status_code=417))]\n\n    def get_app_kwargs(self):\n        return dict(xsrf_cookies=True)\n\n    def test_error_xsrf(self):\n        response = self.fetch('/error', method='POST', body='')\n        self.assertEqual(response.code, 417)\n\n    def test_404_xsrf(self):\n        response = self.fetch('/404', method='POST', body='')\n        self.assertEqual(response.code, 404)\n\n\nclass GzipTestCase(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        def get(self):\n            if self.get_argument('vary', None):\n                self.set_header('Vary', self.get_argument('vary'))\n            self.write('hello world')\n\n    def get_app_kwargs(self):\n        return dict(gzip=True)\n\n    def test_gzip(self):\n        response = self.fetch('/')\n        self.assertEqual(response.headers['Content-Encoding'], 'gzip')\n        self.assertEqual(response.headers['Vary'], 'Accept-Encoding')\n\n    def test_gzip_not_requested(self):\n        response = self.fetch('/', use_gzip=False)\n        self.assertNotIn('Content-Encoding', response.headers)\n        self.assertEqual(response.headers['Vary'], 'Accept-Encoding')\n\n    def test_vary_already_present(self):\n        response = self.fetch('/?vary=Accept-Language')\n        self.assertEqual(response.headers['Vary'],\n                         'Accept-Language, Accept-Encoding')\n\n\n@wsgi_safe\nclass PathArgsInPrepareTest(WebTestCase):\n    class Handler(RequestHandler):\n        def prepare(self):\n            self.write(dict(args=self.path_args, kwargs=self.path_kwargs))\n\n        def get(self, path):\n            assert path == 'foo'\n            self.finish()\n\n    def get_handlers(self):\n        return [('/pos/(.*)', self.Handler),\n                ('/kw/(?P<path>.*)', self.Handler)]\n\n    def test_pos(self):\n        response = self.fetch('/pos/foo')\n        response.rethrow()\n        data = json_decode(response.body)\n        self.assertEqual(data, {'args': ['foo'], 'kwargs': {}})\n\n    def test_kw(self):\n        response = self.fetch('/kw/foo')\n        response.rethrow()\n        data = json_decode(response.body)\n        self.assertEqual(data, {'args': [], 'kwargs': {'path': 'foo'}})\n\n\n@wsgi_safe\nclass ClearAllCookiesTest(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        def get(self):\n            self.clear_all_cookies()\n            self.write('ok')\n\n    def test_clear_all_cookies(self):\n        response = self.fetch('/', headers={'Cookie': 'foo=bar; baz=xyzzy'})\n        set_cookies = sorted(response.headers.get_list('Set-Cookie'))\n        self.assertTrue(set_cookies[0].startswith('baz=;'))\n        self.assertTrue(set_cookies[1].startswith('foo=;'))\n\n\nclass PermissionError(Exception):\n    pass\n\n\n@wsgi_safe\nclass ExceptionHandlerTest(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        def get(self):\n            exc = self.get_argument('exc')\n            if exc == 'http':\n                raise HTTPError(410, \"no longer here\")\n            elif exc == 'zero':\n                1 / 0\n            elif exc == 'permission':\n                raise PermissionError('not allowed')\n\n        def write_error(self, status_code, **kwargs):\n            if 'exc_info' in kwargs:\n                typ, value, tb = kwargs['exc_info']\n                if isinstance(value, PermissionError):\n                    self.set_status(403)\n                    self.write('PermissionError')\n                    return\n            RequestHandler.write_error(self, status_code, **kwargs)\n\n        def log_exception(self, typ, value, tb):\n            if isinstance(value, PermissionError):\n                app_log.warning('custom logging for PermissionError: %s',\n                                value.args[0])\n            else:\n                RequestHandler.log_exception(self, typ, value, tb)\n\n    def test_http_error(self):\n        # HTTPErrors are logged as warnings with no stack trace.\n        # TODO: extend ExpectLog to test this more precisely\n        with ExpectLog(gen_log, '.*no longer here'):\n            response = self.fetch('/?exc=http')\n            self.assertEqual(response.code, 410)\n\n    def test_unknown_error(self):\n        # Unknown errors are logged as errors with a stack trace.\n        with ExpectLog(app_log, 'Uncaught exception'):\n            response = self.fetch('/?exc=zero')\n            self.assertEqual(response.code, 500)\n\n    def test_known_error(self):\n        # log_exception can override logging behavior, and write_error\n        # can override the response.\n        with ExpectLog(app_log,\n                       'custom logging for PermissionError: not allowed'):\n            response = self.fetch('/?exc=permission')\n            self.assertEqual(response.code, 403)\n\n\n@wsgi_safe\nclass UIMethodUIModuleTest(SimpleHandlerTestCase):\n    \"\"\"Test that UI methods and modules are created correctly and\n    associated with the handler.\n    \"\"\"\n    class Handler(RequestHandler):\n        def get(self):\n            self.render('foo.html')\n\n        def value(self):\n            return self.get_argument(\"value\")\n\n    def get_app_kwargs(self):\n        def my_ui_method(handler, x):\n            return \"In my_ui_method(%s) with handler value %s.\" % (\n                x, handler.value())\n        class MyModule(UIModule):\n            def render(self, x):\n                return \"In MyModule(%s) with handler value %s.\" % (\n                    x, self.handler.value())\n\n        loader = DictLoader({\n            'foo.html': '{{ my_ui_method(42) }} {% module MyModule(123) %}',\n        })\n        return dict(template_loader=loader,\n                    ui_methods={'my_ui_method': my_ui_method},\n                    ui_modules={'MyModule': MyModule})\n\n    def tearDown(self):\n        super(UIMethodUIModuleTest, self).tearDown()\n        # TODO: fix template loader caching so this isn't necessary.\n        RequestHandler._template_loaders.clear()\n\n    def test_ui_method(self):\n        response = self.fetch('/?value=asdf')\n        self.assertEqual(response.body,\n                         b'In my_ui_method(42) with handler value asdf. '\n                         b'In MyModule(123) with handler value asdf.')\n\n\n@wsgi_safe\nclass GetArgumentErrorTest(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        def get(self):\n            try:\n                self.get_argument('foo')\n                self.write({})\n            except MissingArgumentError as e:\n                self.write({'arg_name': e.arg_name,\n                            'log_message': e.log_message})\n\n    def test_catch_error(self):\n        response = self.fetch('/')\n        self.assertEqual(json_decode(response.body),\n                         {'arg_name': 'foo',\n                          'log_message': 'Missing argument foo'})\n\n\nclass MultipleExceptionTest(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        exc_count = 0\n\n        @asynchronous\n        def get(self):\n            from tornado.ioloop import IOLoop\n            IOLoop.current().add_callback(lambda: 1 / 0)\n            IOLoop.current().add_callback(lambda: 1 / 0)\n\n        def log_exception(self, typ, value, tb):\n            MultipleExceptionTest.Handler.exc_count += 1\n\n    def test_multi_exception(self):\n        # This test verifies that multiple exceptions raised into the same\n        # ExceptionStackContext do not generate extraneous log entries\n        # due to \"Cannot send error response after headers written\".\n        # log_exception is called, but it does not proceed to send_error.\n        response = self.fetch('/')\n        self.assertEqual(response.code, 500)\n        response = self.fetch('/')\n        self.assertEqual(response.code, 500)\n        # Each of our two requests generated two exceptions, we should have\n        # seen at least three of them by now (the fourth may still be\n        # in the queue).\n        self.assertGreater(MultipleExceptionTest.Handler.exc_count, 2)\n\n\n@wsgi_safe\nclass SetCurrentUserTest(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        def prepare(self):\n            self.current_user = 'Ben'\n\n        def get(self):\n            self.write('Hello %s' % self.current_user)\n\n    def test_set_current_user(self):\n        # Ensure that current_user can be assigned to normally for apps\n        # that want to forgo the lazy get_current_user property\n        response = self.fetch('/')\n        self.assertEqual(response.body, b'Hello Ben')\n\n\n@wsgi_safe\nclass GetCurrentUserTest(WebTestCase):\n    def get_app_kwargs(self):\n        class WithoutUserModule(UIModule):\n            def render(self):\n                return ''\n\n        class WithUserModule(UIModule):\n            def render(self):\n                return str(self.current_user)\n\n        loader = DictLoader({\n            'without_user.html': '',\n            'with_user.html': '{{ current_user }}',\n            'without_user_module.html': '{% module WithoutUserModule() %}',\n            'with_user_module.html': '{% module WithUserModule() %}',\n        })\n        return dict(template_loader=loader,\n                    ui_modules={'WithUserModule': WithUserModule,\n                                'WithoutUserModule': WithoutUserModule})\n\n    def tearDown(self):\n        super(GetCurrentUserTest, self).tearDown()\n        RequestHandler._template_loaders.clear()\n\n    def get_handlers(self):\n        class CurrentUserHandler(RequestHandler):\n            def prepare(self):\n                self.has_loaded_current_user = False\n\n            def get_current_user(self):\n                self.has_loaded_current_user = True\n                return ''\n\n        class WithoutUserHandler(CurrentUserHandler):\n            def get(self):\n                self.render_string('without_user.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class WithUserHandler(CurrentUserHandler):\n            def get(self):\n                self.render_string('with_user.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class CurrentUserModuleHandler(CurrentUserHandler):\n            def get_template_namespace(self):\n                # If RequestHandler.get_template_namespace is called, then\n                # get_current_user is evaluated. Until #820 is fixed, this\n                # is a small hack to circumvent the issue.\n                return self.ui\n\n        class WithoutUserModuleHandler(CurrentUserModuleHandler):\n            def get(self):\n                self.render_string('without_user_module.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        class WithUserModuleHandler(CurrentUserModuleHandler):\n            def get(self):\n                self.render_string('with_user_module.html')\n                self.finish(str(self.has_loaded_current_user))\n\n        return [('/without_user', WithoutUserHandler),\n                ('/with_user', WithUserHandler),\n                ('/without_user_module', WithoutUserModuleHandler),\n                ('/with_user_module', WithUserModuleHandler)]\n\n    @unittest.skip('needs fix')\n    def test_get_current_user_is_lazy(self):\n        # TODO: Make this test pass. See #820.\n        response = self.fetch('/without_user')\n        self.assertEqual(response.body, b'False')\n\n    def test_get_current_user_works(self):\n        response = self.fetch('/with_user')\n        self.assertEqual(response.body, b'True')\n\n    def test_get_current_user_from_ui_module_is_lazy(self):\n        response = self.fetch('/without_user_module')\n        self.assertEqual(response.body, b'False')\n\n    def test_get_current_user_from_ui_module_works(self):\n        response = self.fetch('/with_user_module')\n        self.assertEqual(response.body, b'True')\n\n\n@wsgi_safe\nclass UnimplementedHTTPMethodsTest(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        pass\n\n    def test_unimplemented_standard_methods(self):\n        for method in ['HEAD', 'GET', 'DELETE', 'OPTIONS']:\n            response = self.fetch('/', method=method)\n            self.assertEqual(response.code, 405)\n        for method in ['POST', 'PUT']:\n            response = self.fetch('/', method=method, body=b'')\n            self.assertEqual(response.code, 405)\n\n\nclass UnimplementedNonStandardMethodsTest(SimpleHandlerTestCase):\n    # wsgiref.validate complains about unknown methods in a way that makes\n    # this test not wsgi_safe.\n    class Handler(RequestHandler):\n        def other(self):\n            # Even though this method exists, it won't get called automatically\n            # because it is not in SUPPORTED_METHODS.\n            self.write('other')\n\n    def test_unimplemented_patch(self):\n        # PATCH is recently standardized; Tornado supports it by default\n        # but wsgiref.validate doesn't like it.\n        response = self.fetch('/', method='PATCH', body=b'')\n        self.assertEqual(response.code, 405)\n\n    def test_unimplemented_other(self):\n        response = self.fetch('/', method='OTHER',\n                              allow_nonstandard_methods=True)\n        self.assertEqual(response.code, 405)\n\n\n@wsgi_safe\nclass AllHTTPMethodsTest(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        def method(self):\n            self.write(self.request.method)\n\n        get = delete = options = post = put = method\n\n    def test_standard_methods(self):\n        response = self.fetch('/', method='HEAD')\n        self.assertEqual(response.body, b'')\n        for method in ['GET', 'DELETE', 'OPTIONS']:\n            response = self.fetch('/', method=method)\n            self.assertEqual(response.body, utf8(method))\n        for method in ['POST', 'PUT']:\n            response = self.fetch('/', method=method, body=b'')\n            self.assertEqual(response.body, utf8(method))\n\n\nclass PatchMethodTest(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        SUPPORTED_METHODS = RequestHandler.SUPPORTED_METHODS + ('OTHER',)\n\n        def patch(self):\n            self.write('patch')\n\n        def other(self):\n            self.write('other')\n\n    def test_patch(self):\n        response = self.fetch('/', method='PATCH', body=b'')\n        self.assertEqual(response.body, b'patch')\n\n    def test_other(self):\n        response = self.fetch('/', method='OTHER',\n                              allow_nonstandard_methods=True)\n        self.assertEqual(response.body, b'other')\n\n\n@wsgi_safe\nclass FinishInPrepareTest(SimpleHandlerTestCase):\n    class Handler(RequestHandler):\n        def prepare(self):\n            self.finish('done')\n\n        def get(self):\n            # It's difficult to assert for certain that a method did not\n            # or will not be called in an asynchronous context, but this\n            # will be logged noisily if it is reached.\n            raise Exception('should not reach this method')\n\n    def test_finish_in_prepare(self):\n        response = self.fetch('/')\n        self.assertEqual(response.body, b'done')\n",
        "#!/usr/bin/env python\nimport unittest\nimport sys\nimport time\nimport traceback\nimport platform\nimport os\n\n\nclass PytestLikeResult(unittest.TestResult):\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        self.start_time = None\n        # Store (test, outcome, info) for each test:\n        #   outcome ∈ { \"passed\", \"failed\", \"error\", \"skipped\" }\n        #   info can hold the exception or skip reason, etc.\n        self.results = []\n\n    def startTestRun(self):\n        \"\"\"Called once before all tests.\"\"\"\n        self.start_time = time.time()\n        # Print a header similar to pytest\n        print(\"=\" * 29 + \" test session starts \" + \"=\" * 29)\n        # You can customize the platform/versions/paths as you like:\n        print(\n            f\"platform {platform.system().lower()} -- Python {platform.python_version()}\"\n        )\n        print(f\"rootdir: {os.path.abspath(os.curdir)}\")\n\n    def stopTestRun(self):\n        \"\"\"Called once after all tests are done.\"\"\"\n        elapsed = time.time() - self.start_time\n        print()  # blank line after final dot\n\n        # Summarize\n        ntests = len(self.results)\n        print(f\"collected {ntests} items\")\n\n        # Show details of failures/errors\n        failures = [r for r in self.results if r[1] == \"failed\"]\n        errors = [r for r in self.results if r[1] == \"error\"]\n\n        if failures:\n            print(\"\\n\" + \"=\" * 35 + \" FAILURES \" + \"=\" * 35)\n            for test, outcome, err_info in failures:\n                test = test.split(\"::\")\n                if len(test) == 3:\n                    test = f\"{test[1]}.{test[2]}\"\n                else:\n                    test = f\"{test[1]}\"\n                print(f\"__________ {test} __________\")\n                self._print_traceback(err_info)\n        if errors:\n            print(\"\\n\" + \"=\" * 35 + \" ERRORS \" + \"=\" * 37)\n            for test, outcome, err_info in errors:\n                test = test.split(\"::\")\n                if len(test) == 3:\n                    test = f\"{test[1]}.{test[2]}\"\n                else:\n                    test = f\"{test[1]}\"\n                print(f\"__________ {test} __________\")\n                self._print_traceback(err_info)\n\n        # Optional short summary lines for passes/fails/skips\n        print(\"\\n==================== short test summary info ====================\")\n        for test, outcome, info in self.results:\n            if outcome in (\"passed\", \"failed\", \"error\", \"skipped\"):\n                print(f\"{outcome.upper()} {test}\")\n\n        # Final one-line summary: “1 failed, 1 errors, 10 passed in 2.04s”\n        passed_count = sum(1 for r in self.results if r[1] == \"passed\")\n        failed_count = len(failures)\n        error_count = len(errors)\n        skipped_count = sum(1 for r in self.results if r[1] == \"skipped\")\n\n        summary_bits = []\n        if failed_count:\n            summary_bits.append(f\"{failed_count} failed\")\n        if error_count:\n            summary_bits.append(f\"{error_count} error{'s' if error_count != 1 else ''}\")\n        if passed_count:\n            summary_bits.append(f\"{passed_count} passed\")\n        if skipped_count:\n            summary_bits.append(f\"{skipped_count} skipped\")\n\n        summary_str = \", \".join(summary_bits) if summary_bits else \"no tests run\"\n        print(\n            f\"=================== {summary_str} in {elapsed:.2f}s ===================\"\n        )\n\n    def startTest(self, test):\n        \"\"\"Called right before each test method.\"\"\"\n        super().startTest(test)\n        # Print a dot or some indicator\n        print(\".\", end=\"\", flush=True)\n\n    def addSuccess(self, test):\n        super().addSuccess(test)\n        self.results.append((self._test_id(test), \"passed\", None))\n\n    def addFailure(self, test, err):\n        super().addFailure(test, err)\n        self.results.append((self._test_id(test), \"failed\", err))\n\n    def addError(self, test, err):\n        super().addError(test, err)\n        self.results.append((self._test_id(test), \"error\", err))\n\n    def addSkip(self, test, reason):\n        super().addSkip(test, reason)\n        self.results.append((self._test_id(test), \"skipped\", reason))\n\n    def _print_traceback(self, err_info):\n        \"\"\"Helper to print the traceback like pytest does.\"\"\"\n        if isinstance(err_info, tuple) and len(err_info) == 3:\n            exc_type, exc_value, tb = err_info\n            traceback.print_exception(exc_type, exc_value, tb, file=sys.stdout)\n        else:\n            print(str(err_info))\n\n    def _test_id(self, test):\n        try:\n            return f\"{test.__class__.__module__}::{test.__class__.__name__}::{test._testMethodName}\"\n        except AttributeError:\n            # Fallback for _ErrorHolder objects\n            return f\"{test.__class__.__module__}::{test.__class__.__name__}\"\n\n\nclass PytestLikeRunner(unittest.TextTestRunner):\n    \"\"\"A custom TextTestRunner that uses the PytestLikeResult.\"\"\"\n\n    resultclass = PytestLikeResult\n\n    def run(self, test):\n        result = self._makeResult()\n        # Overriding run to ensure we call startTestRun/stopTestRun\n        result.startTestRun()\n        test(result)\n        result.stopTestRun()\n        return result\n\n    def tearDown(self):\n        # Reset signal handlers\n        from twisted.internet import reactor\n\n        reactor.removeAll()\n        reactor.stop()\n        super().tearDown()\n\n\ndef main():\n    loader = unittest.TestLoader()\n    suite = loader.discover(\".\", pattern=\"test_*.py\")  # discover tests in r2e_tests/\n    runner = PytestLikeRunner(verbosity=0)\n    result = runner.run(suite)\n    # Exit with code 0 if all tests passed/skipped, 1 if there were fails/errors\n    sys.exit(not result.wasSuccessful())\n\n\nif __name__ == \"__main__\":\n    main()\n"
    ],
    "test_file_names": [
        "test_1.py",
        "tornado_unittest_runner.py"
    ],
    "setup_res_code": 0,
    "setup_res_stdout": "",
    "setup_res_stderr": "Using CPython 3.9.21\nCreating virtual environment at: .venv\nActivate with: source .venv/bin/activate\nResolved 1 package in 806ms\nPrepared 1 package in 826ms\nInstalled 1 package in 0.81ms\n + tornado==3.2.dev1 (from file:///home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef)\nResolved 29 packages in 15ms\nInstalled 29 packages in 30ms\n + attrs==24.3.0\n + automat==24.8.1\n + cachetools==5.5.0\n + cffi==1.17.1\n + chardet==5.2.0\n + colorama==0.4.6\n + constantly==23.10.4\n + distlib==0.3.9\n + exceptiongroup==1.2.2\n + filelock==3.16.1\n + hyperlink==21.0.0\n + idna==3.10\n + incremental==24.7.2\n + iniconfig==2.0.0\n + packaging==24.2\n + platformdirs==4.3.6\n + pluggy==1.5.0\n + pycares==4.5.0\n + pycparser==2.22\n + pycurl==7.45.4\n + pyproject-api==1.8.0\n + pytest==8.3.4\n + setuptools==75.6.0\n + tomli==2.2.1\n + tox==4.23.2\n + twisted==24.11.0\n + typing-extensions==4.12.2\n + virtualenv==20.28.0\n + zope-interface==7.2\n",
    "new_commit_res_code": 1,
    "new_commit_res_stdout": "============================= test session starts =============================\nplatform linux -- Python 3.9.21\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef\n...............................................................................................\ncollected 95 items\n\n=================================== FAILURES ===================================\n__________ ClearAllCookiesTest.test_clear_all_cookies __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 1322, in test_clear_all_cookies\n    self.assertTrue(set_cookies[0].startswith('baz=;'))\nAssertionError: False is not true\n__________ StaticDefaultFilenameTest.test_static_default_filename __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 1002, in test_static_default_filename\n    self.assertEqual(response.code, 200)\nAssertionError: 404 != 200\n__________ StaticDefaultFilenameTest.test_static_default_redirect __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 1007, in test_static_default_redirect\n    self.assertEqual(response.code, 301)\nAssertionError: 404 != 301\n__________ StaticFileTest.test_absolute_static_url __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 815, in test_absolute_static_url\n    self.assertEqual(response.body, (\nAssertionError: b'http://localhost:34025/static/robots.txt' != b'http://localhost:34025/static/robots.txt?v=f71d20196d4caf35b6a670db8c70b03d'\n__________ StaticFileTest.test_static_etag __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 877, in test_static_etag\n    self.assertEqual(utf8(response.headers.get(\"Etag\")),\nAssertionError: None != b'\"f71d20196d4caf35b6a670db8c70b03d\"'\n__________ StaticFileTest.test_static_files __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 803, in test_static_files\n    self.assertTrue(b\"Disallow: /\" in response.body)\nAssertionError: False is not true\n__________ StaticFileTest.test_static_head __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 960, in test_static_head\n    self.assertEqual(response.code, 200)\nAssertionError: 404 != 200\n__________ StaticFileTest.test_static_head_range __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 970, in test_static_head_range\n    self.assertEqual(response.code, 206)\nAssertionError: 404 != 206\n__________ StaticFileTest.test_static_if_modified_since_pre_epoch __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 859, in test_static_if_modified_since_pre_epoch\n    self.assertEqual(response.code, 200)\nAssertionError: 404 != 200\n__________ StaticFileTest.test_static_invalid_range __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 942, in test_static_invalid_range\n    self.assertEqual(response.code, 200)\nAssertionError: 404 != 200\n__________ StaticFileTest.test_static_range_if_none_match __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 980, in test_static_range_if_none_match\n    self.assertEqual(response.code, 304)\nAssertionError: 404 != 304\n__________ StaticFileTest.test_static_unsatisfiable_range_invalid_start __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 954, in test_static_unsatisfiable_range_invalid_start\n    self.assertEqual(response.code, 416)\nAssertionError: 404 != 416\n__________ StaticFileTest.test_static_unsatisfiable_range_zero_suffix __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 947, in test_static_unsatisfiable_range_zero_suffix\n    self.assertEqual(response.headers.get(\"Content-Range\"),\nAssertionError: None != 'bytes */26'\n__________ StaticFileTest.test_static_url __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 810, in test_static_url\n    self.assertEqual(response.body,\nAssertionError: b'/static/robots.txt' != b'/static/robots.txt?v=f71d20196d4caf35b6a670db8c70b03d'\n__________ StaticFileTest.test_static_with_range __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 883, in test_static_with_range\n    self.assertEqual(response.code, 206)\nAssertionError: 404 != 206\n__________ StaticFileTest.test_static_with_range_end_edge __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 926, in test_static_with_range_end_edge\n    self.assertEqual(response.body, b\": /\\n\")\nAssertionError: b'<html><title>404: Not Found</title><body>404: Not Found</body></html>' != b': /\\n'\n__________ StaticFileTest.test_static_with_range_full_file __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 896, in test_static_with_range_full_file\n    self.assertEqual(response.code, 200)\nAssertionError: 404 != 200\n__________ StaticFileTest.test_static_with_range_full_past_end __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 906, in test_static_with_range_full_past_end\n    self.assertEqual(response.code, 200)\nAssertionError: 404 != 200\n__________ StaticFileTest.test_static_with_range_neg_end __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 934, in test_static_with_range_neg_end\n    self.assertEqual(response.body, b\": /\\n\")\nAssertionError: b'<html><title>404: Not Found</title><body>404: Not Found</body></html>' != b': /\\n'\n__________ StaticFileTest.test_static_with_range_partial_past_end __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 916, in test_static_with_range_partial_past_end\n    self.assertEqual(response.code, 206)\nAssertionError: 404 != 206\n__________ StaticFileWithPathTest.test_serve __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 1024, in test_serve\n    self.assertEqual(response.body, b\"H\\xc3\\xa9llo\\n\")\nAssertionError: b'<html><title>404: Not Found</title><body>404: Not Found</body></html>' != b'H\\xc3\\xa9llo\\n'\n\n=================================== ERRORS =====================================\n__________ StaticFileTest.test_static_304_if_modified_since __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 842, in test_static_304_if_modified_since\n    'If-Modified-Since': response1.headers['Last-Modified']})\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/tornado/httputil.py\", line 191, in __getitem__\n    return dict.__getitem__(self, _normalized_headers[name])\nKeyError: 'Last-Modified'\n__________ StaticFileTest.test_static_304_if_none_match __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 850, in test_static_304_if_none_match\n    'If-None-Match': response1.headers['Etag']})\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/tornado/httputil.py\", line 191, in __getitem__\n    return dict.__getitem__(self, _normalized_headers[name])\nKeyError: 'Etag'\n__________ StaticFileTest.test_static_if_modified_since_time_zone __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 866, in test_static_if_modified_since_time_zone\n    stat = os.stat(relpath('static/robots.txt'))\nFileNotFoundError: [Errno 2] No such file or directory: '/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/static/robots.txt'\n\n==================== short test summary info ====================\nPASSED r2e_tests.test_1::AllHTTPMethodsTest::test_standard_methods\nPASSED r2e_tests.test_1::AuthRedirectTest::test_absolute_auth_redirect\nPASSED r2e_tests.test_1::AuthRedirectTest::test_relative_auth_redirect\nFAILED r2e_tests.test_1::ClearAllCookiesTest::test_clear_all_cookies\nPASSED r2e_tests.test_1::ClearHeaderTest::test_clear_header\nPASSED r2e_tests.test_1::ConnectionCloseTest::test_connection_close\nPASSED r2e_tests.test_1::CookieTest::test_cookie_special_char\nPASSED r2e_tests.test_1::CookieTest::test_get_cookie\nPASSED r2e_tests.test_1::CookieTest::test_set_cookie\nPASSED r2e_tests.test_1::CookieTest::test_set_cookie_domain\nPASSED r2e_tests.test_1::CookieTest::test_set_cookie_overwrite\nPASSED r2e_tests.test_1::CustomStaticFileTest::test_serve\nPASSED r2e_tests.test_1::CustomStaticFileTest::test_static_url\nPASSED r2e_tests.test_1::DateHeaderTest::test_date_header\nPASSED r2e_tests.test_1::ErrorHandlerXSRFTest::test_404_xsrf\nPASSED r2e_tests.test_1::ErrorHandlerXSRFTest::test_error_xsrf\nPASSED r2e_tests.test_1::ErrorResponseTest::test_default\nPASSED r2e_tests.test_1::ErrorResponseTest::test_failed_write_error\nPASSED r2e_tests.test_1::ErrorResponseTest::test_get_error_html\nPASSED r2e_tests.test_1::ErrorResponseTest::test_write_error\nPASSED r2e_tests.test_1::ExceptionHandlerTest::test_http_error\nPASSED r2e_tests.test_1::ExceptionHandlerTest::test_known_error\nPASSED r2e_tests.test_1::ExceptionHandlerTest::test_unknown_error\nPASSED r2e_tests.test_1::FinishInPrepareTest::test_finish_in_prepare\nPASSED r2e_tests.test_1::GetArgumentErrorTest::test_catch_error\nPASSED r2e_tests.test_1::GetCurrentUserTest::test_get_current_user_from_ui_module_is_lazy\nPASSED r2e_tests.test_1::GetCurrentUserTest::test_get_current_user_from_ui_module_works\nSKIPPED r2e_tests.test_1::GetCurrentUserTest::test_get_current_user_is_lazy\nPASSED r2e_tests.test_1::GetCurrentUserTest::test_get_current_user_works\nPASSED r2e_tests.test_1::GzipTestCase::test_gzip\nPASSED r2e_tests.test_1::GzipTestCase::test_gzip_not_requested\nPASSED r2e_tests.test_1::GzipTestCase::test_vary_already_present\nPASSED r2e_tests.test_1::Header304Test::test_304_headers\nPASSED r2e_tests.test_1::HostMatchingTest::test_host_matching\nPASSED r2e_tests.test_1::MultipleExceptionTest::test_multi_exception\nPASSED r2e_tests.test_1::NamedURLSpecGroupsTest::test_named_urlspec_groups\nPASSED r2e_tests.test_1::NonWSGIWebTests::test_empty_flush\nPASSED r2e_tests.test_1::NonWSGIWebTests::test_flow_control\nPASSED r2e_tests.test_1::PatchMethodTest::test_other\nPASSED r2e_tests.test_1::PatchMethodTest::test_patch\nPASSED r2e_tests.test_1::PathArgsInPrepareTest::test_kw\nPASSED r2e_tests.test_1::PathArgsInPrepareTest::test_pos\nPASSED r2e_tests.test_1::RaiseWithReasonTest::test_httperror_str\nPASSED r2e_tests.test_1::RaiseWithReasonTest::test_raise_with_reason\nPASSED r2e_tests.test_1::RequestEncodingTest::test_group_encoding\nPASSED r2e_tests.test_1::RequestEncodingTest::test_group_question_mark\nPASSED r2e_tests.test_1::RequestEncodingTest::test_slashes\nPASSED r2e_tests.test_1::SecureCookieTest::test_arbitrary_bytes\nPASSED r2e_tests.test_1::SecureCookieTest::test_cookie_tampering_future_timestamp\nPASSED r2e_tests.test_1::SecureCookieTest::test_round_trip\nPASSED r2e_tests.test_1::SetCurrentUserTest::test_set_current_user\nFAILED r2e_tests.test_1::StaticDefaultFilenameTest::test_static_default_filename\nFAILED r2e_tests.test_1::StaticDefaultFilenameTest::test_static_default_redirect\nFAILED r2e_tests.test_1::StaticFileTest::test_absolute_static_url\nPASSED r2e_tests.test_1::StaticFileTest::test_absolute_version_exclusion\nPASSED r2e_tests.test_1::StaticFileTest::test_include_host_override\nPASSED r2e_tests.test_1::StaticFileTest::test_relative_version_exclusion\nERROR r2e_tests.test_1::StaticFileTest::test_static_304_if_modified_since\nERROR r2e_tests.test_1::StaticFileTest::test_static_304_if_none_match\nPASSED r2e_tests.test_1::StaticFileTest::test_static_404\nFAILED r2e_tests.test_1::StaticFileTest::test_static_etag\nFAILED r2e_tests.test_1::StaticFileTest::test_static_files\nFAILED r2e_tests.test_1::StaticFileTest::test_static_head\nFAILED r2e_tests.test_1::StaticFileTest::test_static_head_range\nFAILED r2e_tests.test_1::StaticFileTest::test_static_if_modified_since_pre_epoch\nERROR r2e_tests.test_1::StaticFileTest::test_static_if_modified_since_time_zone\nFAILED r2e_tests.test_1::StaticFileTest::test_static_invalid_range\nFAILED r2e_tests.test_1::StaticFileTest::test_static_range_if_none_match\nFAILED r2e_tests.test_1::StaticFileTest::test_static_unsatisfiable_range_invalid_start\nFAILED r2e_tests.test_1::StaticFileTest::test_static_unsatisfiable_range_zero_suffix\nFAILED r2e_tests.test_1::StaticFileTest::test_static_url\nFAILED r2e_tests.test_1::StaticFileTest::test_static_with_range\nFAILED r2e_tests.test_1::StaticFileTest::test_static_with_range_end_edge\nFAILED r2e_tests.test_1::StaticFileTest::test_static_with_range_full_file\nFAILED r2e_tests.test_1::StaticFileTest::test_static_with_range_full_past_end\nFAILED r2e_tests.test_1::StaticFileTest::test_static_with_range_neg_end\nFAILED r2e_tests.test_1::StaticFileTest::test_static_with_range_partial_past_end\nFAILED r2e_tests.test_1::StaticFileWithPathTest::test_serve\nPASSED r2e_tests.test_1::StatusReasonTest::test_status\nPASSED r2e_tests.test_1::UIMethodUIModuleTest::test_ui_method\nPASSED r2e_tests.test_1::UnimplementedHTTPMethodsTest::test_unimplemented_standard_methods\nPASSED r2e_tests.test_1::UnimplementedNonStandardMethodsTest::test_unimplemented_other\nPASSED r2e_tests.test_1::UnimplementedNonStandardMethodsTest::test_unimplemented_patch\nPASSED r2e_tests.test_1::WSGISafeWebTest::test_decode_argument\nPASSED r2e_tests.test_1::WSGISafeWebTest::test_decode_argument_plus\nPASSED r2e_tests.test_1::WSGISafeWebTest::test_get_argument\nPASSED r2e_tests.test_1::WSGISafeWebTest::test_header_injection\nPASSED r2e_tests.test_1::WSGISafeWebTest::test_multi_header\nPASSED r2e_tests.test_1::WSGISafeWebTest::test_no_gzip\nPASSED r2e_tests.test_1::WSGISafeWebTest::test_optional_path\nPASSED r2e_tests.test_1::WSGISafeWebTest::test_redirect\nPASSED r2e_tests.test_1::WSGISafeWebTest::test_reverse_url\nPASSED r2e_tests.test_1::WSGISafeWebTest::test_types\nPASSED r2e_tests.test_1::WSGISafeWebTest::test_uimodule_resources\nPASSED r2e_tests.test_1::WSGISafeWebTest::test_uimodule_unescaped\n=================== 21 failed, 3 errors, 70 passed, 1 skipped in 0.20s ===================\n",
    "new_commit_res_stderr": "WARNING:tornado.access:405 HEAD / (127.0.0.1) 0.31ms\nWARNING:tornado.access:404 POST /404 (127.0.0.1) 0.27ms\nWARNING:tornado.access:417 POST /error (127.0.0.1) 0.20ms\nERROR:tornado.access:500 GET /default (127.0.0.1) 0.31ms\nERROR:tornado.access:503 GET /default?status=503 (127.0.0.1) 0.16ms\nERROR:tornado.access:500 GET /failed_write_error (127.0.0.1) 0.35ms\nERROR:tornado.access:500 GET /get_error_html (127.0.0.1) 0.19ms\nERROR:tornado.access:503 GET /get_error_html?status=503 (127.0.0.1) 0.17ms\nERROR:tornado.access:500 GET /write_error (127.0.0.1) 0.19ms\nERROR:tornado.access:503 GET /write_error?status=503 (127.0.0.1) 0.16ms\nWARNING:tornado.access:410 GET /?exc=http (127.0.0.1) 0.23ms\nWARNING:tornado.access:403 GET /?exc=permission (127.0.0.1) 0.26ms\nERROR:tornado.access:500 GET /?exc=zero (127.0.0.1) 0.21ms\nWARNING:tornado.access:404 GET /bar (127.0.0.1) 0.13ms\nWARNING:tornado.access:404 GET /baz (127.0.0.1) 0.14ms\nERROR:tornado.access:500 GET / (127.0.0.1) 0.19ms\nERROR:tornado.access:500 GET / (127.0.0.1) 0.18ms\nERROR:tornado.access:682 GET / (127.0.0.1) 0.15ms\nWARNING:tornado.access:404 GET /static/dir/ (127.0.0.1) 0.30ms\nWARNING:tornado.access:404 GET /static/dir (127.0.0.1) 0.27ms\nERROR:tornado.general:Could not open static file '/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/static/robots.txt'\nWARNING:tornado.access:404 GET /static/robots.txt (127.0.0.1) 0.19ms\nWARNING:tornado.access:404 GET /static/robots.txt (127.0.0.1) 0.27ms\nWARNING:tornado.access:404 GET /static/blarg (127.0.0.1) 0.25ms\nWARNING:tornado.access:404 GET /static/robots.txt (127.0.0.1) 0.33ms\nWARNING:tornado.access:404 GET /robots.txt (127.0.0.1) 0.28ms\nWARNING:tornado.access:404 HEAD /static/robots.txt (127.0.0.1) 0.49ms\nWARNING:tornado.access:404 HEAD /static/robots.txt (127.0.0.1) 0.23ms\nWARNING:tornado.access:404 GET /static/robots.txt (127.0.0.1) 0.31ms\nWARNING:tornado.access:404 GET /static/robots.txt (127.0.0.1) 0.28ms\nWARNING:tornado.access:404 GET /static/robots.txt (127.0.0.1) 0.28ms\nWARNING:tornado.access:404 GET /static/robots.txt (127.0.0.1) 0.43ms\nWARNING:tornado.access:404 GET /static/robots.txt (127.0.0.1) 0.39ms\nWARNING:tornado.access:404 GET /static/robots.txt (127.0.0.1) 0.40ms\nWARNING:tornado.access:404 GET /static/robots.txt (127.0.0.1) 0.38ms\nWARNING:tornado.access:404 GET /static/robots.txt (127.0.0.1) 0.40ms\nWARNING:tornado.access:404 GET /static/robots.txt (127.0.0.1) 0.39ms\nWARNING:tornado.access:404 GET /static/robots.txt (127.0.0.1) 0.39ms\nWARNING:tornado.access:404 GET /static/robots.txt (127.0.0.1) 0.30ms\nWARNING:tornado.access:404 GET /foo/utf8.html (127.0.0.1) 0.30ms\nERROR:tornado.access:682 GET /?code=682&reason=Bar (127.0.0.1) 0.19ms\nERROR:tornado.access:500 GET /?code=682 (127.0.0.1) 0.38ms\nWARNING:tornado.access:405 HEAD / (127.0.0.1) 0.23ms\nWARNING:tornado.access:405 GET / (127.0.0.1) 0.22ms\nWARNING:tornado.access:405 DELETE / (127.0.0.1) 0.23ms\nWARNING:tornado.access:405 OPTIONS / (127.0.0.1) 0.22ms\nWARNING:tornado.access:405 POST / (127.0.0.1) 0.24ms\nWARNING:tornado.access:405 PUT / (127.0.0.1) 0.23ms\nWARNING:tornado.access:405 OTHER / (127.0.0.1) 0.28ms\nWARNING:tornado.access:405 PATCH / (127.0.0.1) 0.33ms\n",
    "old_commit_res_code": 1,
    "old_commit_res_stdout": "============================= test session starts =============================\nplatform linux -- Python 3.9.21\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef\n...............................................................................................\ncollected 95 items\n\n=================================== FAILURES ===================================\n__________ ClearAllCookiesTest.test_clear_all_cookies __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 1322, in test_clear_all_cookies\n    self.assertTrue(set_cookies[0].startswith('baz=;'))\nAssertionError: False is not true\n__________ GetCurrentUserTest.test_get_current_user_from_ui_module_is_lazy __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 1560, in test_get_current_user_from_ui_module_is_lazy\n    self.assertEqual(response.body, b'False')\nAssertionError: b'True' != b'False'\n__________ StaticDefaultFilenameTest.test_static_default_filename __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 1002, in test_static_default_filename\n    self.assertEqual(response.code, 200)\nAssertionError: 404 != 200\n__________ StaticDefaultFilenameTest.test_static_default_redirect __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 1007, in test_static_default_redirect\n    self.assertEqual(response.code, 301)\nAssertionError: 404 != 301\n__________ StaticFileTest.test_absolute_static_url __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 815, in test_absolute_static_url\n    self.assertEqual(response.body, (\nAssertionError: b'http://localhost:36881/static/robots.txt' != b'http://localhost:36881/static/robots.txt?v=f71d20196d4caf35b6a670db8c70b03d'\n__________ StaticFileTest.test_static_etag __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 877, in test_static_etag\n    self.assertEqual(utf8(response.headers.get(\"Etag\")),\nAssertionError: None != b'\"f71d20196d4caf35b6a670db8c70b03d\"'\n__________ StaticFileTest.test_static_files __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 803, in test_static_files\n    self.assertTrue(b\"Disallow: /\" in response.body)\nAssertionError: False is not true\n__________ StaticFileTest.test_static_head __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 960, in test_static_head\n    self.assertEqual(response.code, 200)\nAssertionError: 404 != 200\n__________ StaticFileTest.test_static_head_range __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 970, in test_static_head_range\n    self.assertEqual(response.code, 206)\nAssertionError: 404 != 206\n__________ StaticFileTest.test_static_if_modified_since_pre_epoch __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 859, in test_static_if_modified_since_pre_epoch\n    self.assertEqual(response.code, 200)\nAssertionError: 404 != 200\n__________ StaticFileTest.test_static_invalid_range __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 942, in test_static_invalid_range\n    self.assertEqual(response.code, 200)\nAssertionError: 404 != 200\n__________ StaticFileTest.test_static_range_if_none_match __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 980, in test_static_range_if_none_match\n    self.assertEqual(response.code, 304)\nAssertionError: 404 != 304\n__________ StaticFileTest.test_static_unsatisfiable_range_invalid_start __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 954, in test_static_unsatisfiable_range_invalid_start\n    self.assertEqual(response.code, 416)\nAssertionError: 404 != 416\n__________ StaticFileTest.test_static_unsatisfiable_range_zero_suffix __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 947, in test_static_unsatisfiable_range_zero_suffix\n    self.assertEqual(response.headers.get(\"Content-Range\"),\nAssertionError: None != 'bytes */26'\n__________ StaticFileTest.test_static_url __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 810, in test_static_url\n    self.assertEqual(response.body,\nAssertionError: b'/static/robots.txt' != b'/static/robots.txt?v=f71d20196d4caf35b6a670db8c70b03d'\n__________ StaticFileTest.test_static_with_range __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 883, in test_static_with_range\n    self.assertEqual(response.code, 206)\nAssertionError: 404 != 206\n__________ StaticFileTest.test_static_with_range_end_edge __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 926, in test_static_with_range_end_edge\n    self.assertEqual(response.body, b\": /\\n\")\nAssertionError: b'<html><title>404: Not Found</title><body>404: Not Found</body></html>' != b': /\\n'\n__________ StaticFileTest.test_static_with_range_full_file __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 896, in test_static_with_range_full_file\n    self.assertEqual(response.code, 200)\nAssertionError: 404 != 200\n__________ StaticFileTest.test_static_with_range_full_past_end __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 906, in test_static_with_range_full_past_end\n    self.assertEqual(response.code, 200)\nAssertionError: 404 != 200\n__________ StaticFileTest.test_static_with_range_neg_end __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 934, in test_static_with_range_neg_end\n    self.assertEqual(response.body, b\": /\\n\")\nAssertionError: b'<html><title>404: Not Found</title><body>404: Not Found</body></html>' != b': /\\n'\n__________ StaticFileTest.test_static_with_range_partial_past_end __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 916, in test_static_with_range_partial_past_end\n    self.assertEqual(response.code, 206)\nAssertionError: 404 != 206\n__________ StaticFileWithPathTest.test_serve __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 1024, in test_serve\n    self.assertEqual(response.body, b\"H\\xc3\\xa9llo\\n\")\nAssertionError: b'<html><title>404: Not Found</title><body>404: Not Found</body></html>' != b'H\\xc3\\xa9llo\\n'\n\n=================================== ERRORS =====================================\n__________ StaticFileTest.test_static_304_if_modified_since __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 842, in test_static_304_if_modified_since\n    'If-Modified-Since': response1.headers['Last-Modified']})\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/tornado/httputil.py\", line 191, in __getitem__\n    return dict.__getitem__(self, _normalized_headers[name])\nKeyError: 'Last-Modified'\n__________ StaticFileTest.test_static_304_if_none_match __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 850, in test_static_304_if_none_match\n    'If-None-Match': response1.headers['Etag']})\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/tornado/httputil.py\", line 191, in __getitem__\n    return dict.__getitem__(self, _normalized_headers[name])\nKeyError: 'Etag'\n__________ StaticFileTest.test_static_if_modified_since_time_zone __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/test_1.py\", line 866, in test_static_if_modified_since_time_zone\n    stat = os.stat(relpath('static/robots.txt'))\nFileNotFoundError: [Errno 2] No such file or directory: '/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/static/robots.txt'\n\n==================== short test summary info ====================\nPASSED r2e_tests.test_1::AllHTTPMethodsTest::test_standard_methods\nPASSED r2e_tests.test_1::AuthRedirectTest::test_absolute_auth_redirect\nPASSED r2e_tests.test_1::AuthRedirectTest::test_relative_auth_redirect\nFAILED r2e_tests.test_1::ClearAllCookiesTest::test_clear_all_cookies\nPASSED r2e_tests.test_1::ClearHeaderTest::test_clear_header\nPASSED r2e_tests.test_1::ConnectionCloseTest::test_connection_close\nPASSED r2e_tests.test_1::CookieTest::test_cookie_special_char\nPASSED r2e_tests.test_1::CookieTest::test_get_cookie\nPASSED r2e_tests.test_1::CookieTest::test_set_cookie\nPASSED r2e_tests.test_1::CookieTest::test_set_cookie_domain\nPASSED r2e_tests.test_1::CookieTest::test_set_cookie_overwrite\nPASSED r2e_tests.test_1::CustomStaticFileTest::test_serve\nPASSED r2e_tests.test_1::CustomStaticFileTest::test_static_url\nPASSED r2e_tests.test_1::DateHeaderTest::test_date_header\nPASSED r2e_tests.test_1::ErrorHandlerXSRFTest::test_404_xsrf\nPASSED r2e_tests.test_1::ErrorHandlerXSRFTest::test_error_xsrf\nPASSED r2e_tests.test_1::ErrorResponseTest::test_default\nPASSED r2e_tests.test_1::ErrorResponseTest::test_failed_write_error\nPASSED r2e_tests.test_1::ErrorResponseTest::test_get_error_html\nPASSED r2e_tests.test_1::ErrorResponseTest::test_write_error\nPASSED r2e_tests.test_1::ExceptionHandlerTest::test_http_error\nPASSED r2e_tests.test_1::ExceptionHandlerTest::test_known_error\nPASSED r2e_tests.test_1::ExceptionHandlerTest::test_unknown_error\nPASSED r2e_tests.test_1::FinishInPrepareTest::test_finish_in_prepare\nPASSED r2e_tests.test_1::GetArgumentErrorTest::test_catch_error\nFAILED r2e_tests.test_1::GetCurrentUserTest::test_get_current_user_from_ui_module_is_lazy\nPASSED r2e_tests.test_1::GetCurrentUserTest::test_get_current_user_from_ui_module_works\nSKIPPED r2e_tests.test_1::GetCurrentUserTest::test_get_current_user_is_lazy\nPASSED r2e_tests.test_1::GetCurrentUserTest::test_get_current_user_works\nPASSED r2e_tests.test_1::GzipTestCase::test_gzip\nPASSED r2e_tests.test_1::GzipTestCase::test_gzip_not_requested\nPASSED r2e_tests.test_1::GzipTestCase::test_vary_already_present\nPASSED r2e_tests.test_1::Header304Test::test_304_headers\nPASSED r2e_tests.test_1::HostMatchingTest::test_host_matching\nPASSED r2e_tests.test_1::MultipleExceptionTest::test_multi_exception\nPASSED r2e_tests.test_1::NamedURLSpecGroupsTest::test_named_urlspec_groups\nPASSED r2e_tests.test_1::NonWSGIWebTests::test_empty_flush\nPASSED r2e_tests.test_1::NonWSGIWebTests::test_flow_control\nPASSED r2e_tests.test_1::PatchMethodTest::test_other\nPASSED r2e_tests.test_1::PatchMethodTest::test_patch\nPASSED r2e_tests.test_1::PathArgsInPrepareTest::test_kw\nPASSED r2e_tests.test_1::PathArgsInPrepareTest::test_pos\nPASSED r2e_tests.test_1::RaiseWithReasonTest::test_httperror_str\nPASSED r2e_tests.test_1::RaiseWithReasonTest::test_raise_with_reason\nPASSED r2e_tests.test_1::RequestEncodingTest::test_group_encoding\nPASSED r2e_tests.test_1::RequestEncodingTest::test_group_question_mark\nPASSED r2e_tests.test_1::RequestEncodingTest::test_slashes\nPASSED r2e_tests.test_1::SecureCookieTest::test_arbitrary_bytes\nPASSED r2e_tests.test_1::SecureCookieTest::test_cookie_tampering_future_timestamp\nPASSED r2e_tests.test_1::SecureCookieTest::test_round_trip\nPASSED r2e_tests.test_1::SetCurrentUserTest::test_set_current_user\nFAILED r2e_tests.test_1::StaticDefaultFilenameTest::test_static_default_filename\nFAILED r2e_tests.test_1::StaticDefaultFilenameTest::test_static_default_redirect\nFAILED r2e_tests.test_1::StaticFileTest::test_absolute_static_url\nPASSED r2e_tests.test_1::StaticFileTest::test_absolute_version_exclusion\nPASSED r2e_tests.test_1::StaticFileTest::test_include_host_override\nPASSED r2e_tests.test_1::StaticFileTest::test_relative_version_exclusion\nERROR r2e_tests.test_1::StaticFileTest::test_static_304_if_modified_since\nERROR r2e_tests.test_1::StaticFileTest::test_static_304_if_none_match\nPASSED r2e_tests.test_1::StaticFileTest::test_static_404\nFAILED r2e_tests.test_1::StaticFileTest::test_static_etag\nFAILED r2e_tests.test_1::StaticFileTest::test_static_files\nFAILED r2e_tests.test_1::StaticFileTest::test_static_head\nFAILED r2e_tests.test_1::StaticFileTest::test_static_head_range\nFAILED r2e_tests.test_1::StaticFileTest::test_static_if_modified_since_pre_epoch\nERROR r2e_tests.test_1::StaticFileTest::test_static_if_modified_since_time_zone\nFAILED r2e_tests.test_1::StaticFileTest::test_static_invalid_range\nFAILED r2e_tests.test_1::StaticFileTest::test_static_range_if_none_match\nFAILED r2e_tests.test_1::StaticFileTest::test_static_unsatisfiable_range_invalid_start\nFAILED r2e_tests.test_1::StaticFileTest::test_static_unsatisfiable_range_zero_suffix\nFAILED r2e_tests.test_1::StaticFileTest::test_static_url\nFAILED r2e_tests.test_1::StaticFileTest::test_static_with_range\nFAILED r2e_tests.test_1::StaticFileTest::test_static_with_range_end_edge\nFAILED r2e_tests.test_1::StaticFileTest::test_static_with_range_full_file\nFAILED r2e_tests.test_1::StaticFileTest::test_static_with_range_full_past_end\nFAILED r2e_tests.test_1::StaticFileTest::test_static_with_range_neg_end\nFAILED r2e_tests.test_1::StaticFileTest::test_static_with_range_partial_past_end\nFAILED r2e_tests.test_1::StaticFileWithPathTest::test_serve\nPASSED r2e_tests.test_1::StatusReasonTest::test_status\nPASSED r2e_tests.test_1::UIMethodUIModuleTest::test_ui_method\nPASSED r2e_tests.test_1::UnimplementedHTTPMethodsTest::test_unimplemented_standard_methods\nPASSED r2e_tests.test_1::UnimplementedNonStandardMethodsTest::test_unimplemented_other\nPASSED r2e_tests.test_1::UnimplementedNonStandardMethodsTest::test_unimplemented_patch\nPASSED r2e_tests.test_1::WSGISafeWebTest::test_decode_argument\nPASSED r2e_tests.test_1::WSGISafeWebTest::test_decode_argument_plus\nPASSED r2e_tests.test_1::WSGISafeWebTest::test_get_argument\nPASSED r2e_tests.test_1::WSGISafeWebTest::test_header_injection\nPASSED r2e_tests.test_1::WSGISafeWebTest::test_multi_header\nPASSED r2e_tests.test_1::WSGISafeWebTest::test_no_gzip\nPASSED r2e_tests.test_1::WSGISafeWebTest::test_optional_path\nPASSED r2e_tests.test_1::WSGISafeWebTest::test_redirect\nPASSED r2e_tests.test_1::WSGISafeWebTest::test_reverse_url\nPASSED r2e_tests.test_1::WSGISafeWebTest::test_types\nPASSED r2e_tests.test_1::WSGISafeWebTest::test_uimodule_resources\nPASSED r2e_tests.test_1::WSGISafeWebTest::test_uimodule_unescaped\n=================== 22 failed, 3 errors, 69 passed, 1 skipped in 0.14s ===================\n",
    "old_commit_res_stderr": "WARNING:tornado.access:405 HEAD / (127.0.0.1) 0.20ms\nWARNING:tornado.access:404 POST /404 (127.0.0.1) 0.17ms\nWARNING:tornado.access:417 POST /error (127.0.0.1) 0.16ms\nERROR:tornado.access:500 GET /default (127.0.0.1) 0.25ms\nERROR:tornado.access:503 GET /default?status=503 (127.0.0.1) 0.15ms\nERROR:tornado.access:500 GET /failed_write_error (127.0.0.1) 0.21ms\nERROR:tornado.access:500 GET /get_error_html (127.0.0.1) 0.36ms\nERROR:tornado.access:503 GET /get_error_html?status=503 (127.0.0.1) 0.17ms\nERROR:tornado.access:500 GET /write_error (127.0.0.1) 0.21ms\nERROR:tornado.access:503 GET /write_error?status=503 (127.0.0.1) 0.14ms\nWARNING:tornado.access:410 GET /?exc=http (127.0.0.1) 0.23ms\nWARNING:tornado.access:403 GET /?exc=permission (127.0.0.1) 0.21ms\nERROR:tornado.access:500 GET /?exc=zero (127.0.0.1) 0.19ms\nWARNING:tornado.access:404 GET /bar (127.0.0.1) 0.13ms\nWARNING:tornado.access:404 GET /baz (127.0.0.1) 0.12ms\nERROR:tornado.access:500 GET / (127.0.0.1) 0.17ms\nERROR:tornado.access:500 GET / (127.0.0.1) 0.15ms\nERROR:tornado.access:682 GET / (127.0.0.1) 0.14ms\nWARNING:tornado.access:404 GET /static/dir/ (127.0.0.1) 0.18ms\nWARNING:tornado.access:404 GET /static/dir (127.0.0.1) 0.21ms\nERROR:tornado.general:Could not open static file '/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e93e9b493028f5848b9d7929087a335d615cef/r2e_tests/static/robots.txt'\nWARNING:tornado.access:404 GET /static/robots.txt (127.0.0.1) 0.18ms\nWARNING:tornado.access:404 GET /static/robots.txt (127.0.0.1) 0.16ms\nWARNING:tornado.access:404 GET /static/blarg (127.0.0.1) 0.20ms\nWARNING:tornado.access:404 GET /static/robots.txt (127.0.0.1) 0.19ms\nWARNING:tornado.access:404 GET /robots.txt (127.0.0.1) 0.17ms\nWARNING:tornado.access:404 HEAD /static/robots.txt (127.0.0.1) 0.21ms\nWARNING:tornado.access:404 HEAD /static/robots.txt (127.0.0.1) 0.18ms\nWARNING:tornado.access:404 GET /static/robots.txt (127.0.0.1) 0.18ms\nWARNING:tornado.access:404 GET /static/robots.txt (127.0.0.1) 0.17ms\nWARNING:tornado.access:404 GET /static/robots.txt (127.0.0.1) 0.22ms\nWARNING:tornado.access:404 GET /static/robots.txt (127.0.0.1) 0.17ms\nWARNING:tornado.access:404 GET /static/robots.txt (127.0.0.1) 0.18ms\nWARNING:tornado.access:404 GET /static/robots.txt (127.0.0.1) 0.18ms\nWARNING:tornado.access:404 GET /static/robots.txt (127.0.0.1) 0.23ms\nWARNING:tornado.access:404 GET /static/robots.txt (127.0.0.1) 0.17ms\nWARNING:tornado.access:404 GET /static/robots.txt (127.0.0.1) 0.18ms\nWARNING:tornado.access:404 GET /static/robots.txt (127.0.0.1) 0.18ms\nWARNING:tornado.access:404 GET /static/robots.txt (127.0.0.1) 0.18ms\nWARNING:tornado.access:404 GET /foo/utf8.html (127.0.0.1) 0.19ms\nERROR:tornado.access:682 GET /?code=682&reason=Bar (127.0.0.1) 0.13ms\nERROR:tornado.access:500 GET /?code=682 (127.0.0.1) 0.20ms\nWARNING:tornado.access:405 HEAD / (127.0.0.1) 0.14ms\nWARNING:tornado.access:405 GET / (127.0.0.1) 0.15ms\nWARNING:tornado.access:405 DELETE / (127.0.0.1) 0.13ms\nWARNING:tornado.access:405 OPTIONS / (127.0.0.1) 0.13ms\nWARNING:tornado.access:405 POST / (127.0.0.1) 0.16ms\nWARNING:tornado.access:405 PUT / (127.0.0.1) 0.15ms\nWARNING:tornado.access:405 OTHER / (127.0.0.1) 0.14ms\nWARNING:tornado.access:405 PATCH / (127.0.0.1) 0.16ms\n"
}
tornado/test/web_test.py tornado/web.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** `current_user` in UI modules is not lazily evaluated

**Description:**
When using `current_user` within UI modules, it is evaluated immediately during the module's initialization rather than being accessed lazily. This premature evaluation can lead to unexpected behavior, such as unnecessary database queries or incorrect user data being loaded before it's needed.

**Example Buggy Code:**
```python
class UserProfileModule(UIModule):
    def render(self):
        user = self.current_user  # This triggers get_current_user immediately
        if user:
            return f"Hello, {user.name}!"
        return "Hello, Guest!"
```

In the above example, accessing `self.current_user` during the `render` method causes the `get_current_user` method to be called immediately, which may not be desirable in all contexts.

**Expected Behavior:**
The `current_user` property should be accessed lazily, meaning `get_current_user` is called only when `current_user` is explicitly accessed within the UI module. This ensures that user data is loaded only when necessary, improving performance and preventing unintended side effects.

**Actual Behavior:**
`current_user` is evaluated eagerly during the initialization of the UI module, leading to premature calls to `get_current_user`. This results in unnecessary processing and potential inconsistencies in user data handling.

[/ISSUE]
--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.

--- BEGIN FILE ---
```
### tornado/web.py
#!/usr/bin/env python
#
# Copyright 2009 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

"""``tornado.web`` provides a simple web framework with asynchronous
features that allow it to scale to large numbers of open connections,
making it ideal for `long polling
<http://en.wikipedia.org/wiki/Push_technology#Long_polling>`_.

Here is a simple "Hello, world" example app::

    import tornado.ioloop
    import tornado.web

    class MainHandler(tornado.web.RequestHandler):
        def get(self):
            self.write("Hello, world")

    if __name__ == "__main__":
        application = tornado.web.Application([
            (r"/", MainHandler),
        ])
        application.listen(8888)
        tornado.ioloop.IOLoop.instance().start()

See the :doc:`Tornado overview <overview>` for more details and a good getting
started guide.

Thread-safety notes
-------------------

In general, methods on `RequestHandler` and elsewhere in Tornado are
not thread-safe.  In particular, methods such as
`~RequestHandler.write()`, `~RequestHandler.finish()`, and
`~RequestHandler.flush()` must only be called from the main thread.  If
you use multiple threads it is important to use `.IOLoop.add_callback`
to transfer control back to the main thread before finishing the
request.
"""

from __future__ import absolute_import, division, print_function, with_statement


import base64
import binascii
import datetime
import email.utils
import functools
import gzip
import hashlib
import hmac
import mimetypes
import numbers
import os.path
import re
import stat
import sys
import threading
import time
import tornado
import traceback
import types
import uuid

from tornado.concurrent import Future
from tornado import escape
from tornado import httputil
from tornado import locale
from tornado.log import access_log, app_log, gen_log
from tornado import stack_context
from tornado import template
from tornado.escape import utf8, _unicode
from tornado.util import bytes_type, import_object, ObjectDict, raise_exc_info, unicode_type

try:
    from io import BytesIO  # python 3
except ImportError:
    from cStringIO import StringIO as BytesIO  # python 2

try:
    import Cookie  # py2
except ImportError:
    import http.cookies as Cookie  # py3

try:
    import urlparse  # py2
except ImportError:
    import urllib.parse as urlparse  # py3

try:
    from urllib import urlencode  # py2
except ImportError:
    from urllib.parse import urlencode  # py3


class RequestHandler(object):
    """Subclass this class and define `get()` or `post()` to make a handler.

    If you want to support more methods than the standard GET/HEAD/POST, you
    should override the class variable ``SUPPORTED_METHODS`` in your
    `RequestHandler` subclass.
    """
    SUPPORTED_METHODS = ("GET", "HEAD", "POST", "DELETE", "PATCH", "PUT",
                         "OPTIONS")

    _template_loaders = {}  # {path: template.BaseLoader}
    _template_loader_lock = threading.Lock()
    _remove_control_chars_regex = re.compile(r"[\x00-\x08\x0e-\x1f]")

    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)

    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

    @property
    def settings(self):
        """An alias for `self.application.settings <Application.settings>`."""
        return self.application.settings

    def head(self, *args, **kwargs):
        raise HTTPError(405)

    def get(self, *args, **kwargs):
        raise HTTPError(405)

    def post(self, *args, **kwargs):
        raise HTTPError(405)

    def delete(self, *args, **kwargs):
        raise HTTPError(405)

    def patch(self, *args, **kwargs):
        raise HTTPError(405)

    def put(self, *args, **kwargs):
        raise HTTPError(405)

    def options(self, *args, **kwargs):
        raise HTTPError(405)

    def prepare(self):
        """Called at the beginning of a request before  `get`/`post`/etc.

        Override this method to perform common initialization regardless
        of the request method.

        Asynchronous support: Decorate this method with `.gen.coroutine`
        or `.return_future` to make it asynchronous (the
        `asynchronous` decorator cannot be used on `prepare`).
        If this method returns a `.Future` execution will not proceed
        until the `.Future` is done.

        .. versionadded:: 3.1
           Asynchronous support.
        """
        pass

    def on_finish(self):
        """Called after the end of a request.

        Override this method to perform cleanup, logging, etc.
        This method is a counterpart to `prepare`.  ``on_finish`` may
        not produce any output, as it is called after the response
        has been sent to the client.
        """
        pass

    def on_connection_close(self):
        """Called in async handlers if the client closed the connection.

        Override this to clean up resources associated with
        long-lived connections.  Note that this method is called only if
        the connection was closed during asynchronous processing; if you
        need to do cleanup after every request override `on_finish`
        instead.

        Proxies may keep a connection open for a time (perhaps
        indefinitely) after the client has gone away, so this method
        may not be called promptly after the end user closes their
        connection.
        """
        pass

    def clear(self):
        """Resets all headers and content for this response."""
        self._headers = httputil.HTTPHeaders({
            "Server": "TornadoServer/%s" % tornado.version,
            "Content-Type": "text/html; charset=UTF-8",
            "Date": httputil.format_timestamp(time.time()),
        })
        self.set_default_headers()
        if (not self.request.supports_http_1_1() and
            getattr(self.request, 'connection', None) and
                not self.request.connection.no_keep_alive):
            conn_header = self.request.headers.get("Connection")
            if conn_header and (conn_header.lower() == "keep-alive"):
                self.set_header("Connection", "Keep-Alive")
        self._write_buffer = []
        self._status_code = 200
        self._reason = httputil.responses[200]

    def set_default_headers(self):
        """Override this to set HTTP headers at the beginning of the request.

        For example, this is the place to set a custom ``Server`` header.
        Note that setting such headers in the normal flow of request
        processing may not do what you want, since headers may be reset
        during error handling.
        """
        pass

    def set_status(self, status_code, reason=None):
        """Sets the status code for our response.

        :arg int status_code: Response status code. If ``reason`` is ``None``,
            it must be present in `httplib.responses <http.client.responses>`.
        :arg string reason: Human-readable reason phrase describing the status
            code. If ``None``, it will be filled in from
            `httplib.responses <http.client.responses>`.
        """
        self._status_code = status_code
        if reason is not None:
            self._reason = escape.native_str(reason)
        else:
            try:
                self._reason = httputil.responses[status_code]
            except KeyError:
                raise ValueError("unknown status code %d", status_code)

    def get_status(self):
        """Returns the status code for our response."""
        return self._status_code

    def set_header(self, name, value):
        """Sets the given response header name and value.

        If a datetime is given, we automatically format it according to the
        HTTP specification. If the value is not a string, we convert it to
        a string. All header values are then encoded as UTF-8.
        """
        self._headers[name] = self._convert_header_value(value)

    def add_header(self, name, value):
        """Adds the given response header and value.

        Unlike `set_header`, `add_header` may be called multiple times
        to return multiple values for the same header.
        """
        self._headers.add(name, self._convert_header_value(value))

    def clear_header(self, name):
        """Clears an outgoing header, undoing a previous `set_header` call.

        Note that this method does not apply to multi-valued headers
        set by `add_header`.
        """
        if name in self._headers:
            del self._headers[name]

    _INVALID_HEADER_CHAR_RE = re.compile(br"[\x00-\x1f]")

    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

    _ARG_DEFAULT = []

    def get_argument(self, name, default=_ARG_DEFAULT, strip=True):
        """Returns the value of the argument with the given name.

        If default is not provided, the argument is considered to be
        required, and we raise a `MissingArgumentError` if it is missing.

        If the argument appears in the url more than once, we return the
        last value.

        The returned value is always unicode.
        """
        args = self.get_arguments(name, strip=strip)
        if not args:
            if default is self._ARG_DEFAULT:
                raise MissingArgumentError(name)
            return default
        return args[-1]

    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

    def decode_argument(self, value, name=None):
        """Decodes an argument from the request.

        The argument has been percent-decoded and is now a byte string.
        By default, this method decodes the argument as utf-8 and returns
        a unicode string, but this may be overridden in subclasses.

        This method is used as a filter for both `get_argument()` and for
        values extracted from the url and passed to `get()`/`post()`/etc.

        The name of the argument is provided if known, but may be None
        (e.g. for unnamed groups in the url regex).
        """
        return _unicode(value)

    @property
    def cookies(self):
        """An alias for `self.request.cookies <.httpserver.HTTPRequest.cookies>`."""
        return self.request.cookies

    def get_cookie(self, name, default=None):
        """Gets the value of the cookie with the given name, else default."""
        if self.request.cookies is not None and name in self.request.cookies:
            return self.request.cookies[name].value
        return default

    def set_cookie(self, name, value, domain=None, expires=None, path="/",
                   expires_days=None, **kwargs):
        """Sets the given cookie name/value with the given options.

        Additional keyword arguments are set on the Cookie.Morsel
        directly.
        See http://docs.python.org/library/cookie.html#morsel-objects
        for available attributes.
        """
        # The cookie library only accepts type str, in both python 2 and 3
        name = escape.native_str(name)
        value = escape.native_str(value)
        if re.search(r"[\x00-\x20]", name + value):
            # Don't let us accidentally inject bad stuff
            raise ValueError("Invalid cookie %r: %r" % (name, value))
        if not hasattr(self, "_new_cookie"):
            self._new_cookie = Cookie.SimpleCookie()
        if name in self._new_cookie:
            del self._new_cookie[name]
        self._new_cookie[name] = value
        morsel = self._new_cookie[name]
        if domain:
            morsel["domain"] = domain
        if expires_days is not None and not expires:
            expires = datetime.datetime.utcnow() + datetime.timedelta(
                days=expires_days)
        if expires:
            morsel["expires"] = httputil.format_timestamp(expires)
        if path:
            morsel["path"] = path
        for k, v in kwargs.items():
            if k == 'max_age':
                k = 'max-age'
            morsel[k] = v

    def clear_cookie(self, name, path="/", domain=None):
        """Deletes the cookie with the given name."""
        expires = datetime.datetime.utcnow() - datetime.timedelta(days=365)
        self.set_cookie(name, value="", path=path, expires=expires,
                        domain=domain)

    def clear_all_cookies(self):
        """Deletes all the cookies the user sent with this request."""
        for name in self.request.cookies:
            self.clear_cookie(name)

    def set_secure_cookie(self, name, value, expires_days=30, **kwargs):
        """Signs and timestamps a cookie so it cannot be forged.

        You must specify the ``cookie_secret`` setting in your Application
        to use this method. It should be a long, random sequence of bytes
        to be used as the HMAC secret for the signature.

        To read a cookie set with this method, use `get_secure_cookie()`.

        Note that the ``expires_days`` parameter sets the lifetime of the
        cookie in the browser, but is independent of the ``max_age_days``
        parameter to `get_secure_cookie`.

        Secure cookies may contain arbitrary byte values, not just unicode
        strings (unlike regular cookies)
        """
        self.set_cookie(name, self.create_signed_value(name, value),
                        expires_days=expires_days, **kwargs)

    def create_signed_value(self, name, value):
        """Signs and timestamps a string so it cannot be forged.

        Normally used via set_secure_cookie, but provided as a separate
        method for non-cookie uses.  To decode a value not stored
        as a cookie use the optional value argument to get_secure_cookie.
        """
        self.require_setting("cookie_secret", "secure cookies")
        return create_signed_value(self.application.settings["cookie_secret"],
                                   name, value)

    def get_secure_cookie(self, name, value=None, max_age_days=31):
        """Returns the given signed cookie if it validates, or None.

        The decoded cookie value is returned as a byte string (unlike
        `get_cookie`).
        """
        self.require_setting("cookie_secret", "secure cookies")
        if value is None:
            value = self.get_cookie(name)
        return decode_signed_value(self.application.settings["cookie_secret"],
                                   name, value, max_age_days=max_age_days)

    def redirect(self, url, permanent=False, status=None):
        """Sends a redirect to the given (optionally relative) URL.

        If the ``status`` argument is specified, that value is used as the
        HTTP status code; otherwise either 301 (permanent) or 302
        (temporary) is chosen based on the ``permanent`` argument.
        The default is 302 (temporary).
        """
        if self._headers_written:
            raise Exception("Cannot redirect after headers have been written")
        if status is None:
            status = 301 if permanent else 302
        else:
            assert isinstance(status, int) and 300 <= status <= 399
        self.set_status(status)
        self.set_header("Location", urlparse.urljoin(utf8(self.request.uri),
                                                     utf8(url)))
        self.finish()

    def write(self, chunk):
        """Writes the given chunk to the output buffer.

        To write the output to the network, use the flush() method below.

        If the given chunk is a dictionary, we write it as JSON and set
        the Content-Type of the response to be ``application/json``.
        (if you want to send JSON as a different ``Content-Type``, call
        set_header *after* calling write()).

        Note that lists are not converted to JSON because of a potential
        cross-site security vulnerability.  All JSON output should be
        wrapped in a dictionary.  More details at
        http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
        """
        if self._finished:
            raise RuntimeError("Cannot write() after finish().  May be caused "
                               "by using async operations without the "
                               "@asynchronous decorator.")
        if isinstance(chunk, dict):
            chunk = escape.json_encode(chunk)
            self.set_header("Content-Type", "application/json; charset=UTF-8")
        chunk = utf8(chunk)
        self._write_buffer.append(chunk)

    def render(self, template_name, **kwargs):
        """Renders the template with the given arguments as the response."""
        html = self.render_string(template_name, **kwargs)

        # Insert the additional JS and CSS added by the modules on the page
        js_embed = []
        js_files = []
        css_embed = []
        css_files = []
        html_heads = []
        html_bodies = []
        for module in getattr(self, "_active_modules", {}).values():
            embed_part = module.embedded_javascript()
            if embed_part:
                js_embed.append(utf8(embed_part))
            file_part = module.javascript_files()
            if file_part:
                if isinstance(file_part, (unicode_type, bytes_type)):
                    js_files.append(file_part)
                else:
                    js_files.extend(file_part)
            embed_part = module.embedded_css()
            if embed_part:
                css_embed.append(utf8(embed_part))
            file_part = module.css_files()
            if file_part:
                if isinstance(file_part, (unicode_type, bytes_type)):
                    css_files.append(file_part)
                else:
                    css_files.extend(file_part)
            head_part = module.html_head()
            if head_part:
                html_heads.append(utf8(head_part))
            body_part = module.html_body()
            if body_part:
                html_bodies.append(utf8(body_part))

        def is_absolute(path):
            return any(path.startswith(x) for x in ["/", "http:", "https:"])
        if js_files:
            # Maintain order of JavaScript files given by modules
            paths = []
            unique_paths = set()
            for path in js_files:
                if not is_absolute(path):
                    path = self.static_url(path)
                if path not in unique_paths:
                    paths.append(path)
                    unique_paths.add(path)
            js = ''.join('<script src="' + escape.xhtml_escape(p) +
                         '" type="text/javascript"></script>'
                         for p in paths)
            sloc = html.rindex(b'</body>')
            html = html[:sloc] + utf8(js) + b'\n' + html[sloc:]
        if js_embed:
            js = b'<script type="text/javascript">\n//<![CDATA[\n' + \
                b'\n'.join(js_embed) + b'\n//]]>\n</script>'
            sloc = html.rindex(b'</body>')
            html = html[:sloc] + js + b'\n' + html[sloc:]
        if css_files:
            paths = []
            unique_paths = set()
            for path in css_files:
                if not is_absolute(path):
                    path = self.static_url(path)
                if path not in unique_paths:
                    paths.append(path)
                    unique_paths.add(path)
            css = ''.join('<link href="' + escape.xhtml_escape(p) + '" '
                          'type="text/css" rel="stylesheet"/>'
                          for p in paths)
            hloc = html.index(b'</head>')
            html = html[:hloc] + utf8(css) + b'\n' + html[hloc:]
        if css_embed:
            css = b'<style type="text/css">\n' + b'\n'.join(css_embed) + \
                b'\n</style>'
            hloc = html.index(b'</head>')
            html = html[:hloc] + css + b'\n' + html[hloc:]
        if html_heads:
            hloc = html.index(b'</head>')
            html = html[:hloc] + b''.join(html_heads) + b'\n' + html[hloc:]
        if html_bodies:
            hloc = html.index(b'</body>')
            html = html[:hloc] + b''.join(html_bodies) + b'\n' + html[hloc:]
        self.finish(html)

    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)

    def get_template_namespace(self):
        """Returns a dictionary to be used as the default template namespace.

        May be overridden by subclasses to add or modify values.

        The results of this method will be combined with additional
        defaults in the `tornado.template` module and keyword arguments
        to `render` or `render_string`.
        """
        namespace = dict(
            handler=self,
            request=self.request,
            current_user=self.current_user,
            locale=self.locale,
            _=self.locale.translate,
            static_url=self.static_url,
            xsrf_form_html=self.xsrf_form_html,
            reverse_url=self.reverse_url
        )
        namespace.update(self.ui)
        return namespace

    def create_template_loader(self, template_path):
        """Returns a new template loader for the given path.

        May be overridden by subclasses.  By default returns a
        directory-based loader on the given path, using the
        ``autoescape`` application setting.  If a ``template_loader``
        application setting is supplied, uses that instead.
        """
        settings = self.application.settings
        if "template_loader" in settings:
            return settings["template_loader"]
        kwargs = {}
        if "autoescape" in settings:
            # autoescape=None means "no escaping", so we have to be sure
            # to only pass this kwarg if the user asked for it.
            kwargs["autoescape"] = settings["autoescape"]
        return template.Loader(template_path, **kwargs)

    def flush(self, include_footers=False, callback=None):
        """Flushes the current output buffer to the network.

        The ``callback`` argument, if given, can be used for flow control:
        it will be run when all flushed data has been written to the socket.
        Note that only one flush callback can be outstanding at a time;
        if another flush occurs before the previous flush's callback
        has been run, the previous callback will be discarded.
        """
        if self.application._wsgi:
            # WSGI applications cannot usefully support flush, so just make
            # it a no-op (and run the callback immediately).
            if callback is not None:
                callback()
            return

        chunk = b"".join(self._write_buffer)
        self._write_buffer = []
        if not self._headers_written:
            self._headers_written = True
            for transform in self._transforms:
                self._status_code, self._headers, chunk = \
                    transform.transform_first_chunk(
                        self._status_code, self._headers, chunk, include_footers)
            headers = self._generate_headers()
        else:
            for transform in self._transforms:
                chunk = transform.transform_chunk(chunk, include_footers)
            headers = b""

        # Ignore the chunk and only write the headers for HEAD requests
        if self.request.method == "HEAD":
            if headers:
                self.request.write(headers, callback=callback)
            return

        self.request.write(headers + chunk, callback=callback)

    def finish(self, chunk=None):
        """Finishes this response, ending the HTTP request."""
        if self._finished:
            raise RuntimeError("finish() called twice.  May be caused "
                               "by using async operations without the "
                               "@asynchronous decorator.")

        if chunk is not None:
            self.write(chunk)

        # Automatically support ETags and add the Content-Length header if
        # we have not flushed any content yet.
        if not self._headers_written:
            if (self._status_code == 200 and
                self.request.method in ("GET", "HEAD") and
                    "Etag" not in self._headers):
                self.set_etag_header()
                if self.check_etag_header():
                    self._write_buffer = []
                    self.set_status(304)
            if self._status_code == 304:
                assert not self._write_buffer, "Cannot send body with 304"
                self._clear_headers_for_304()
            elif "Content-Length" not in self._headers:
                content_length = sum(len(part) for part in self._write_buffer)
                self.set_header("Content-Length", content_length)

        if hasattr(self.request, "connection"):
            # Now that the request is finished, clear the callback we
            # set on the IOStream (which would otherwise prevent the
            # garbage collection of the RequestHandler when there
            # are keepalive connections)
            self.request.connection.stream.set_close_callback(None)

        if not self.application._wsgi:
            self.flush(include_footers=True)
            self.request.finish()
            self._log()
        self._finished = True
        self.on_finish()
        # Break up a reference cycle between this handler and the
        # _ui_module closures to allow for faster GC on CPython.
        self.ui = None

    def send_error(self, status_code=500, **kwargs):
        """Sends the given HTTP error code to the browser.

        If `flush()` has already been called, it is not possible to send
        an error, so this method will simply terminate the response.
        If output has been written but not yet flushed, it will be discarded
        and replaced with the error page.

        Override `write_error()` to customize the error page that is returned.
        Additional keyword arguments are passed through to `write_error`.
        """
        if self._headers_written:
            gen_log.error("Cannot send error response after headers written")
            if not self._finished:
                self.finish()
            return
        self.clear()

        reason = None
        if 'exc_info' in kwargs:
            exception = kwargs['exc_info'][1]
            if isinstance(exception, HTTPError) and exception.reason:
                reason = exception.reason
        self.set_status(status_code, reason=reason)
        try:
            self.write_error(status_code, **kwargs)
        except Exception:
            app_log.error("Uncaught exception in write_error", exc_info=True)
        if not self._finished:
            self.finish()

    def write_error(self, status_code, **kwargs):
        """Override to implement custom error pages.

        ``write_error`` may call `write`, `render`, `set_header`, etc
        to produce output as usual.

        If this error was caused by an uncaught exception (including
        HTTPError), an ``exc_info`` triple will be available as
        ``kwargs["exc_info"]``.  Note that this exception may not be
        the "current" exception for purposes of methods like
        ``sys.exc_info()`` or ``traceback.format_exc``.

        For historical reasons, if a method ``get_error_html`` exists,
        it will be used instead of the default ``write_error`` implementation.
        ``get_error_html`` returned a string instead of producing output
        normally, and had different semantics for exception handling.
        Users of ``get_error_html`` are encouraged to convert their code
        to override ``write_error`` instead.
        """
        if hasattr(self, 'get_error_html'):
            if 'exc_info' in kwargs:
                exc_info = kwargs.pop('exc_info')
                kwargs['exception'] = exc_info[1]
                try:
                    # Put the traceback into sys.exc_info()
                    raise_exc_info(exc_info)
                except Exception:
                    self.finish(self.get_error_html(status_code, **kwargs))
            else:
                self.finish(self.get_error_html(status_code, **kwargs))
            return
        if self.settings.get("debug") and "exc_info" in kwargs:
            # in debug mode, try to send a traceback
            self.set_header('Content-Type', 'text/plain')
            for line in traceback.format_exception(*kwargs["exc_info"]):
                self.write(line)
            self.finish()
        else:
            self.finish("<html><title>%(code)d: %(message)s</title>"
                        "<body>%(code)d: %(message)s</body></html>" % {
                            "code": status_code,
                            "message": self._reason,
                        })

    @property
    def locale(self):
        """The local for the current session.

        Determined by either `get_user_locale`, which you can override to
        set the locale based on, e.g., a user preference stored in a
        database, or `get_browser_locale`, which uses the ``Accept-Language``
        header.
        """
        if not hasattr(self, "_locale"):
            self._locale = self.get_user_locale()
            if not self._locale:
                self._locale = self.get_browser_locale()
                assert self._locale
        return self._locale

    def get_user_locale(self):
        """Override to determine the locale from the authenticated user.

        If None is returned, we fall back to `get_browser_locale()`.

        This method should return a `tornado.locale.Locale` object,
        most likely obtained via a call like ``tornado.locale.get("en")``
        """
        return None

    def get_browser_locale(self, default="en_US"):
        """Determines the user's locale from ``Accept-Language`` header.

        See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
        """
        if "Accept-Language" in self.request.headers:
            languages = self.request.headers["Accept-Language"].split(",")
            locales = []
            for language in languages:
                parts = language.strip().split(";")
                if len(parts) > 1 and parts[1].startswith("q="):
                    try:
                        score = float(parts[1][2:])
                    except (ValueError, TypeError):
                        score = 0.0
                else:
                    score = 1.0
                locales.append((parts[0], score))
            if locales:
                locales.sort(key=lambda pair: pair[1], reverse=True)
                codes = [l[0] for l in locales]
                return locale.get(*codes)
        return locale.get(default)

    @property
    def current_user(self):
        """The authenticated user for this request.

        This is a cached version of `get_current_user`, which you can
        override to set the user based on, e.g., a cookie. If that
        method is not overridden, this method always returns None.

        We lazy-load the current user the first time this method is called
        and cache the result after that.
        """
        if not hasattr(self, "_current_user"):
            self._current_user = self.get_current_user()
        return self._current_user

    @current_user.setter
    def current_user(self, value):
        self._current_user = value

    def get_current_user(self):
        """Override to determine the current user from, e.g., a cookie."""
        return None

    def get_login_url(self):
        """Override to customize the login URL based on the request.

        By default, we use the ``login_url`` application setting.
        """
        self.require_setting("login_url", "@tornado.web.authenticated")
        return self.application.settings["login_url"]

    def get_template_path(self):
        """Override to customize template path for each handler.

        By default, we use the ``template_path`` application setting.
        Return None to load templates relative to the calling file.
        """
        return self.application.settings.get("template_path")

    @property
    def xsrf_token(self):
        """The XSRF-prevention token for the current user/session.

        To prevent cross-site request forgery, we set an '_xsrf' cookie
        and include the same '_xsrf' value as an argument with all POST
        requests. If the two do not match, we reject the form submission
        as a potential forgery.

        See http://en.wikipedia.org/wiki/Cross-site_request_forgery
        """
        if not hasattr(self, "_xsrf_token"):
            token = self.get_cookie("_xsrf")
            if not token:
                token = binascii.b2a_hex(uuid.uuid4().bytes)
                expires_days = 30 if self.current_user else None
                self.set_cookie("_xsrf", token, expires_days=expires_days)
            self._xsrf_token = token
        return self._xsrf_token

    def check_xsrf_cookie(self):
        """Verifies that the ``_xsrf`` cookie matches the ``_xsrf`` argument.

        To prevent cross-site request forgery, we set an ``_xsrf``
        cookie and include the same value as a non-cookie
        field with all ``POST`` requests. If the two do not match, we
        reject the form submission as a potential forgery.

        The ``_xsrf`` value may be set as either a form field named ``_xsrf``
        or in a custom HTTP header named ``X-XSRFToken`` or ``X-CSRFToken``
        (the latter is accepted for compatibility with Django).

        See http://en.wikipedia.org/wiki/Cross-site_request_forgery

        Prior to release 1.1.1, this check was ignored if the HTTP header
        ``X-Requested-With: XMLHTTPRequest`` was present.  This exception
        has been shown to be insecure and has been removed.  For more
        information please see
        http://www.djangoproject.com/weblog/2011/feb/08/security/
        http://weblog.rubyonrails.org/2011/2/8/csrf-protection-bypass-in-ruby-on-rails
        """
        token = (self.get_argument("_xsrf", None) or
                 self.request.headers.get("X-Xsrftoken") or
                 self.request.headers.get("X-Csrftoken"))
        if not token:
            raise HTTPError(403, "'_xsrf' argument missing from POST")
        if self.xsrf_token != token:
            raise HTTPError(403, "XSRF cookie does not match POST argument")

    def xsrf_form_html(self):
        """An HTML ``<input/>`` element to be included with all POST forms.

        It defines the ``_xsrf`` input value, which we check on all POST
        requests to prevent cross-site request forgery. If you have set
        the ``xsrf_cookies`` application setting, you must include this
        HTML within all of your HTML forms.

        In a template, this method should be called with ``{% module
        xsrf_form_html() %}``

        See `check_xsrf_cookie()` above for more information.
        """
        return '<input type="hidden" name="_xsrf" value="' + \
            escape.xhtml_escape(self.xsrf_token) + '"/>'

    def static_url(self, path, include_host=None, **kwargs):
        """Returns a static URL for the given relative static file path.

        This method requires you set the ``static_path`` setting in your
        application (which specifies the root directory of your static
        files).

        This method returns a versioned url (by default appending
        ``?v=<signature>``), which allows the static files to be
        cached indefinitely.  This can be disabled by passing
        ``include_version=False`` (in the default implementation;
        other static file implementations are not required to support
        this, but they may support other options).

        By default this method returns URLs relative to the current
        host, but if ``include_host`` is true the URL returned will be
        absolute.  If this handler has an ``include_host`` attribute,
        that value will be used as the default for all `static_url`
        calls that do not pass ``include_host`` as a keyword argument.

        """
        self.require_setting("static_path", "static_url")
        get_url = self.settings.get("static_handler_class",
                                    StaticFileHandler).make_static_url

        if include_host is None:
            include_host = getattr(self, "include_host", False)

        if include_host:
            base = self.request.protocol + "://" + self.request.host
        else:
            base = ""

        return base + get_url(self.settings, path, **kwargs)

    def async_callback(self, callback, *args, **kwargs):
        """Obsolete - catches exceptions from the wrapped function.

        This function is unnecessary since Tornado 1.1.
        """
        if callback is None:
            return None
        if args or kwargs:
            callback = functools.partial(callback, *args, **kwargs)

        def wrapper(*args, **kwargs):
            try:
                return callback(*args, **kwargs)
            except Exception as e:
                if self._headers_written:
                    app_log.error("Exception after headers written",
                                  exc_info=True)
                else:
                    self._handle_request_exception(e)
        return wrapper

    def require_setting(self, name, feature="this feature"):
        """Raises an exception if the given app setting is not defined."""
        if not self.application.settings.get(name):
            raise Exception("You must define the '%s' setting in your "
                            "application to use %s" % (name, feature))

    def reverse_url(self, name, *args):
        """Alias for `Application.reverse_url`."""
        return self.application.reverse_url(name, *args)

    def compute_etag(self):
        """Computes the etag header to be used for this request.

        By default uses a hash of the content written so far.

        May be overridden to provide custom etag implementations,
        or may return None to disable tornado's default etag support.
        """
        hasher = hashlib.sha1()
        for part in self._write_buffer:
            hasher.update(part)
        return '"%s"' % hasher.hexdigest()

    def set_etag_header(self):
        """Sets the response's Etag header using ``self.compute_etag()``.

        Note: no header will be set if ``compute_etag()`` returns ``None``.

        This method is called automatically when the request is finished.
        """
        etag = self.compute_etag()
        if etag is not None:
            self.set_header("Etag", etag)

    def check_etag_header(self):
        """Checks the ``Etag`` header against requests's ``If-None-Match``.

        Returns ``True`` if the request's Etag matches and a 304 should be
        returned. For example::

            self.set_etag_header()
            if self.check_etag_header():
                self.set_status(304)
                return

        This method is called automatically when the request is finished,
        but may be called earlier for applications that override
        `compute_etag` and want to do an early check for ``If-None-Match``
        before completing the request.  The ``Etag`` header should be set
        (perhaps with `set_etag_header`) before calling this method.
        """
        etag = self._headers.get("Etag")
        inm = utf8(self.request.headers.get("If-None-Match", ""))
        return bool(etag and inm and inm.find(etag) >= 0)

    def _stack_context_handle_exception(self, type, value, traceback):
        try:
            # For historical reasons _handle_request_exception only takes
            # the exception value instead of the full triple,
            # so re-raise the exception to ensure that it's in
            # sys.exc_info()
            raise_exc_info((type, value, traceback))
        except Exception:
            self._handle_request_exception(value)
        return True

    def _execute(self, transforms, *args, **kwargs):
        """Executes this request with the given output transforms."""
        self._transforms = transforms
        try:
            if self.request.method not in self.SUPPORTED_METHODS:
                raise HTTPError(405)
            self.path_args = [self.decode_argument(arg) for arg in args]
            self.path_kwargs = dict((k, self.decode_argument(v, name=k))
                                    for (k, v) in kwargs.items())
            # If XSRF cookies are turned on, reject form submissions without
            # the proper cookie
            if self.request.method not in ("GET", "HEAD", "OPTIONS") and \
                    self.application.settings.get("xsrf_cookies"):
                self.check_xsrf_cookie()
            self._when_complete(self.prepare(), self._execute_method)
        except Exception as e:
            self._handle_request_exception(e)

    def _when_complete(self, result, callback):
        try:
            if result is None:
                callback()
            elif isinstance(result, Future):
                if result.done():
                    if result.result() is not None:
                        raise ValueError('Expected None, got %r' % result.result())
                    callback()
                else:
                    # Delayed import of IOLoop because it's not available
                    # on app engine
                    from tornado.ioloop import IOLoop
                    IOLoop.current().add_future(
                        result, functools.partial(self._when_complete,
                                                  callback=callback))
            else:
                raise ValueError("Expected Future or None, got %r" % result)
        except Exception as e:
            self._handle_request_exception(e)

    def _execute_method(self):
        if not self._finished:
            method = getattr(self, self.request.method.lower())
            self._when_complete(method(*self.path_args, **self.path_kwargs),
                                self._execute_finish)

    def _execute_finish(self):
        if self._auto_finish and not self._finished:
            self.finish()

    def _generate_headers(self):
        reason = self._reason
        lines = [utf8(self.request.version + " " +
                      str(self._status_code) +
                      " " + reason)]
        lines.extend([utf8(n) + b": " + utf8(v) for n, v in self._headers.get_all()])

        if hasattr(self, "_new_cookie"):
            for cookie in self._new_cookie.values():
                lines.append(utf8("Set-Cookie: " + cookie.OutputString(None)))
        return b"\r\n".join(lines) + b"\r\n\r\n"

    def _log(self):
        """Logs the current request.

        Sort of deprecated since this functionality was moved to the
        Application, but left in place for the benefit of existing apps
        that have overridden this method.
        """
        self.application.log_request(self)

    def _request_summary(self):
        return self.request.method + " " + self.request.uri + \
            " (" + self.request.remote_ip + ")"

    def _handle_request_exception(self, e):
        self.log_exception(*sys.exc_info())
        if self._finished:
            # Extra errors after the request has been finished should
            # be logged, but there is no reason to continue to try and
            # send a response.
            return
        if isinstance(e, HTTPError):
            if e.status_code not in httputil.responses and not e.reason:
                gen_log.error("Bad HTTP status code: %d", e.status_code)
                self.send_error(500, exc_info=sys.exc_info())
            else:
                self.send_error(e.status_code, exc_info=sys.exc_info())
        else:
            self.send_error(500, exc_info=sys.exc_info())

    def log_exception(self, typ, value, tb):
        """Override to customize logging of uncaught exceptions.

        By default logs instances of `HTTPError` as warnings without
        stack traces (on the ``tornado.general`` logger), and all
        other exceptions as errors with stack traces (on the
        ``tornado.application`` logger).

        .. versionadded:: 3.1
        """
        if isinstance(value, HTTPError):
            if value.log_message:
                format = "%d %s: " + value.log_message
                args = ([value.status_code, self._request_summary()] +
                        list(value.args))
                gen_log.warning(format, *args)
        else:
            app_log.error("Uncaught exception %s\n%r", self._request_summary(),
                          self.request, exc_info=(typ, value, tb))

    def _ui_module(self, name, module):
        def render(*args, **kwargs):
            if not hasattr(self, "_active_modules"):
                self._active_modules = {}
            if name not in self._active_modules:
                self._active_modules[name] = module(self)
            rendered = self._active_modules[name].render(*args, **kwargs)
            return rendered
        return render

    def _ui_method(self, method):
        return lambda *args, **kwargs: method(self, *args, **kwargs)

    def _clear_headers_for_304(self):
        # 304 responses should not contain entity headers (defined in
        # http://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html#sec7.1)
        # not explicitly allowed by
        # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5
        headers = ["Allow", "Content-Encoding", "Content-Language",
                   "Content-Length", "Content-MD5", "Content-Range",
                   "Content-Type", "Last-Modified"]
        for h in headers:
            self.clear_header(h)


def asynchronous(method):
    """Wrap request handler methods with this if they are asynchronous.

    This decorator is unnecessary if the method is also decorated with
    ``@gen.coroutine`` (it is legal but unnecessary to use the two
    decorators together, in which case ``@asynchronous`` must be
    first).

    This decorator should only be applied to the :ref:`HTTP verb
    methods <verbs>`; its behavior is undefined for any other method.
    This decorator does not *make* a method asynchronous; it tells
    the framework that the method *is* asynchronous.  For this decorator
    to be useful the method must (at least sometimes) do something
    asynchronous.

    If this decorator is given, the response is not finished when the
    method returns. It is up to the request handler to call
    `self.finish() <RequestHandler.finish>` to finish the HTTP
    request. Without this decorator, the request is automatically
    finished when the ``get()`` or ``post()`` method returns. Example::

       class MyRequestHandler(web.RequestHandler):
           @web.asynchronous
           def get(self):
              http = httpclient.AsyncHTTPClient()
              http.fetch("http://friendfeed.com/", self._on_download)

           def _on_download(self, response):
              self.write("Downloaded!")
              self.finish()

    .. versionadded:: 3.1
       The ability to use ``@gen.coroutine`` without ``@asynchronous``.
    """
    # Delay the IOLoop import because it's not available on app engine.
    from tornado.ioloop import IOLoop
    @functools.wraps(method)
    def wrapper(self, *args, **kwargs):
        if self.application._wsgi:
            raise Exception("@asynchronous is not supported for WSGI apps")
        self._auto_finish = False
        with stack_context.ExceptionStackContext(
                self._stack_context_handle_exception):
            result = method(self, *args, **kwargs)
            if isinstance(result, Future):
                # If @asynchronous is used with @gen.coroutine, (but
                # not @gen.engine), we can automatically finish the
                # request when the future resolves.  Additionally,
                # the Future will swallow any exceptions so we need
                # to throw them back out to the stack context to finish
                # the request.
                def future_complete(f):
                    f.result()
                    if not self._finished:
                        self.finish()
                IOLoop.current().add_future(result, future_complete)
            return result
    return wrapper


def removeslash(method):
    """Use this decorator to remove trailing slashes from the request path.

    For example, a request to ``/foo/`` would redirect to ``/foo`` with this
    decorator. Your request handler mapping should use a regular expression
    like ``r'/foo/*'`` in conjunction with using the decorator.
    """
    @functools.wraps(method)
    def wrapper(self, *args, **kwargs):
        if self.request.path.endswith("/"):
            if self.request.method in ("GET", "HEAD"):
                uri = self.request.path.rstrip("/")
                if uri:  # don't try to redirect '/' to ''
                    if self.request.query:
                        uri += "?" + self.request.query
                    self.redirect(uri, permanent=True)
                    return
            else:
                raise HTTPError(404)
        return method(self, *args, **kwargs)
    return wrapper


def addslash(method):
    """Use this decorator to add a missing trailing slash to the request path.

    For example, a request to ``/foo`` would redirect to ``/foo/`` with this
    decorator. Your request handler mapping should use a regular expression
    like ``r'/foo/?'`` in conjunction with using the decorator.
    """
    @functools.wraps(method)
    def wrapper(self, *args, **kwargs):
        if not self.request.path.endswith("/"):
            if self.request.method in ("GET", "HEAD"):
                uri = self.request.path + "/"
                if self.request.query:
                    uri += "?" + self.request.query
                self.redirect(uri, permanent=True)
                return
            raise HTTPError(404)
        return method(self, *args, **kwargs)
    return wrapper


class Application(object):
    """A collection of request handlers that make up a web application.

    Instances of this class are callable and can be passed directly to
    HTTPServer to serve the application::

        application = web.Application([
            (r"/", MainPageHandler),
        ])
        http_server = httpserver.HTTPServer(application)
        http_server.listen(8080)
        ioloop.IOLoop.instance().start()

    The constructor for this class takes in a list of `URLSpec` objects
    or (regexp, request_class) tuples. When we receive requests, we
    iterate over the list in order and instantiate an instance of the
    first request class whose regexp matches the request path.

    Each tuple can contain an optional third element, which should be
    a dictionary if it is present. That dictionary is passed as
    keyword arguments to the contructor of the handler. This pattern
    is used for the `StaticFileHandler` in this example (note that a
    `StaticFileHandler` can be installed automatically with the
    static_path setting described below)::

        application = web.Application([
            (r"/static/(.*)", web.StaticFileHandler, {"path": "/var/www"}),
        ])

    We support virtual hosts with the `add_handlers` method, which takes in
    a host regular expression as the first argument::

        application.add_handlers(r"www\.myhost\.com", [
            (r"/article/([0-9]+)", ArticleHandler),
        ])

    You can serve static files by sending the ``static_path`` setting
    as a keyword argument. We will serve those files from the
    ``/static/`` URI (this is configurable with the
    ``static_url_prefix`` setting), and we will serve ``/favicon.ico``
    and ``/robots.txt`` from the same directory.  A custom subclass of
    `StaticFileHandler` can be specified with the
    ``static_handler_class`` setting.
    """
    def __init__(self, handlers=None, default_host="", transforms=None,
                 wsgi=False, **settings):
        if transforms is None:
            self.transforms = []
            if settings.get("gzip"):
                self.transforms.append(GZipContentEncoding)
            self.transforms.append(ChunkedTransferEncoding)
        else:
            self.transforms = transforms
        self.handlers = []
        self.named_handlers = {}
        self.default_host = default_host
        self.settings = settings
        self.ui_modules = {'linkify': _linkify,
                           'xsrf_form_html': _xsrf_form_html,
                           'Template': TemplateModule,
                           }
        self.ui_methods = {}
        self._wsgi = wsgi
        self._load_ui_modules(settings.get("ui_modules", {}))
        self._load_ui_methods(settings.get("ui_methods", {}))
        if self.settings.get("static_path"):
            path = self.settings["static_path"]
            handlers = list(handlers or [])
            static_url_prefix = settings.get("static_url_prefix",
                                             "/static/")
            static_handler_class = settings.get("static_handler_class",
                                                StaticFileHandler)
            static_handler_args = settings.get("static_handler_args", {})
            static_handler_args['path'] = path
            for pattern in [re.escape(static_url_prefix) + r"(.*)",
                            r"/(favicon\.ico)", r"/(robots\.txt)"]:
                handlers.insert(0, (pattern, static_handler_class,
                                    static_handler_args))
        if handlers:
            self.add_handlers(".*$", handlers)

        # Automatically reload modified modules
        if self.settings.get("debug") and not wsgi:
            from tornado import autoreload
            autoreload.start()

    def listen(self, port, address="", **kwargs):
        """Starts an HTTP server for this application on the given port.

        This is a convenience alias for creating an `.HTTPServer`
        object and calling its listen method.  Keyword arguments not
        supported by `HTTPServer.listen <.TCPServer.listen>` are passed to the
        `.HTTPServer` constructor.  For advanced uses
        (e.g. multi-process mode), do not use this method; create an
        `.HTTPServer` and call its
        `.TCPServer.bind`/`.TCPServer.start` methods directly.

        Note that after calling this method you still need to call
        ``IOLoop.instance().start()`` to start the server.
        """
        # import is here rather than top level because HTTPServer
        # is not importable on appengine
        from tornado.httpserver import HTTPServer
        server = HTTPServer(self, **kwargs)
        server.listen(port, address)

    def add_handlers(self, host_pattern, host_handlers):
        """Appends the given handlers to our handler list.

        Host patterns are processed sequentially in the order they were
        added. All matching patterns will be considered.
        """
        if not host_pattern.endswith("$"):
            host_pattern += "$"
        handlers = []
        # The handlers with the wildcard host_pattern are a special
        # case - they're added in the constructor but should have lower
        # precedence than the more-precise handlers added later.
        # If a wildcard handler group exists, it should always be last
        # in the list, so insert new groups just before it.
        if self.handlers and self.handlers[-1][0].pattern == '.*$':
            self.handlers.insert(-1, (re.compile(host_pattern), handlers))
        else:
            self.handlers.append((re.compile(host_pattern), handlers))

        for spec in host_handlers:
            if isinstance(spec, (tuple, list)):
                assert len(spec) in (2, 3)
                pattern = spec[0]
                handler = spec[1]

                if isinstance(handler, str):
                    # import the Module and instantiate the class
                    # Must be a fully qualified name (module.ClassName)
                    handler = import_object(handler)

                if len(spec) == 3:
                    kwargs = spec[2]
                else:
                    kwargs = {}
                spec = URLSpec(pattern, handler, kwargs)
            handlers.append(spec)
            if spec.name:
                if spec.name in self.named_handlers:
                    app_log.warning(
                        "Multiple handlers named %s; replacing previous value",
                        spec.name)
                self.named_handlers[spec.name] = spec

    def add_transform(self, transform_class):
        self.transforms.append(transform_class)

    def _get_host_handlers(self, request):
        host = request.host.lower().split(':')[0]
        matches = []
        for pattern, handlers in self.handlers:
            if pattern.match(host):
                matches.extend(handlers)
        # Look for default host if not behind load balancer (for debugging)
        if not matches and "X-Real-Ip" not in request.headers:
            for pattern, handlers in self.handlers:
                if pattern.match(self.default_host):
                    matches.extend(handlers)
        return matches or None

    def _load_ui_methods(self, methods):
        if isinstance(methods, types.ModuleType):
            self._load_ui_methods(dict((n, getattr(methods, n))
                                       for n in dir(methods)))
        elif isinstance(methods, list):
            for m in methods:
                self._load_ui_methods(m)
        else:
            for name, fn in methods.items():
                if not name.startswith("_") and hasattr(fn, "__call__") \
                        and name[0].lower() == name[0]:
                    self.ui_methods[name] = fn

    def _load_ui_modules(self, modules):
        if isinstance(modules, types.ModuleType):
            self._load_ui_modules(dict((n, getattr(modules, n))
                                       for n in dir(modules)))
        elif isinstance(modules, list):
            for m in modules:
                self._load_ui_modules(m)
        else:
            assert isinstance(modules, dict)
            for name, cls in modules.items():
                try:
                    if issubclass(cls, UIModule):
                        self.ui_modules[name] = cls
                except TypeError:
                    pass

    def __call__(self, request):
        """Called by HTTPServer to execute the request."""
        transforms = [t(request) for t in self.transforms]
        handler = None
        args = []
        kwargs = {}
        handlers = self._get_host_handlers(request)
        if not handlers:
            handler = RedirectHandler(
                self, request, url="http://" + self.default_host + "/")
        else:
            for spec in handlers:
                match = spec.regex.match(request.path)
                if match:
                    handler = spec.handler_class(self, request, **spec.kwargs)
                    if spec.regex.groups:
                        # None-safe wrapper around url_unescape to handle
                        # unmatched optional groups correctly
                        def unquote(s):
                            if s is None:
                                return s
                            return escape.url_unescape(s, encoding=None,
                                                       plus=False)
                        # Pass matched groups to the handler.  Since
                        # match.groups() includes both named and unnamed groups,
                        # we want to use either groups or groupdict but not both.
                        # Note that args are passed as bytes so the handler can
                        # decide what encoding to use.

                        if spec.regex.groupindex:
                            kwargs = dict(
                                (str(k), unquote(v))
                                for (k, v) in match.groupdict().items())
                        else:
                            args = [unquote(s) for s in match.groups()]
                    break
            if not handler:
                handler = ErrorHandler(self, request, status_code=404)

        # In debug mode, re-compile templates and reload static files on every
        # request so you don't need to restart to see changes
        if self.settings.get("debug"):
            with RequestHandler._template_loader_lock:
                for loader in RequestHandler._template_loaders.values():
                    loader.reset()
            StaticFileHandler.reset()

        handler._execute(transforms, *args, **kwargs)
        return handler

    def reverse_url(self, name, *args):
        """Returns a URL path for handler named ``name``

        The handler must be added to the application as a named `URLSpec`.

        Args will be substituted for capturing groups in the `URLSpec` regex.
        They will be converted to strings if necessary, encoded as utf8,
        and url-escaped.
        """
        if name in self.named_handlers:
            return self.named_handlers[name].reverse(*args)
        raise KeyError("%s not found in named urls" % name)

    def log_request(self, handler):
        """Writes a completed HTTP request to the logs.

        By default writes to the python root logger.  To change
        this behavior either subclass Application and override this method,
        or pass a function in the application settings dictionary as
        ``log_function``.
        """
        if "log_function" in self.settings:
            self.settings["log_function"](handler)
            return
        if handler.get_status() < 400:
            log_method = access_log.info
        elif handler.get_status() < 500:
            log_method = access_log.warning
        else:
            log_method = access_log.error
        request_time = 1000.0 * handler.request.request_time()
        log_method("%d %s %.2fms", handler.get_status(),
                   handler._request_summary(), request_time)


class HTTPError(Exception):
    """An exception that will turn into an HTTP error response.

    Raising an `HTTPError` is a convenient alternative to calling
    `RequestHandler.send_error` since it automatically ends the
    current function.

    :arg int status_code: HTTP status code.  Must be listed in
        `httplib.responses <http.client.responses>` unless the ``reason``
        keyword argument is given.
    :arg string log_message: Message to be written to the log for this error
        (will not be shown to the user unless the `Application` is in debug
        mode).  May contain ``%s``-style placeholders, which will be filled
        in with remaining positional parameters.
    :arg string reason: Keyword-only argument.  The HTTP "reason" phrase
        to pass in the status line along with ``status_code``.  Normally
        determined automatically from ``status_code``, but can be used
        to use a non-standard numeric code.
    """
    def __init__(self, status_code, log_message=None, *args, **kwargs):
        self.status_code = status_code
        self.log_message = log_message
        self.args = args
        self.reason = kwargs.get('reason', None)

    def __str__(self):
        message = "HTTP %d: %s" % (
            self.status_code,
            self.reason or httputil.responses.get(self.status_code, 'Unknown'))
        if self.log_message:
            return message + " (" + (self.log_message % self.args) + ")"
        else:
            return message


class MissingArgumentError(HTTPError):
    """Exception raised by `RequestHandler.get_argument`.

    This is a subclass of `HTTPError`, so if it is uncaught a 400 response
    code will be used instead of 500 (and a stack trace will not be logged).

    .. versionadded:: 3.1
    """
    def __init__(self, arg_name):
        super(MissingArgumentError, self).__init__(
            400, 'Missing argument %s' % arg_name)
        self.arg_name = arg_name


class ErrorHandler(RequestHandler):
    """Generates an error response with ``status_code`` for all requests."""
    def initialize(self, status_code):
        self.set_status(status_code)

    def prepare(self):
        raise HTTPError(self._status_code)

    def check_xsrf_cookie(self):
        # POSTs to an ErrorHandler don't actually have side effects,
        # so we don't need to check the xsrf token.  This allows POSTs
        # to the wrong url to return a 404 instead of 403.
        pass


class RedirectHandler(RequestHandler):
    """Redirects the client to the given URL for all GET requests.

    You should provide the keyword argument ``url`` to the handler, e.g.::

        application = web.Application([
            (r"/oldpath", web.RedirectHandler, {"url": "/newpath"}),
        ])
    """
    def initialize(self, url, permanent=True):
        self._url = url
        self._permanent = permanent

    def get(self):
        self.redirect(self._url, permanent=self._permanent)


class StaticFileHandler(RequestHandler):
    """A simple handler that can serve static content from a directory.

    A `StaticFileHandler` is configured automatically if you pass the
    ``static_path`` keyword argument to `Application`.  This handler
    can be customized with the ``static_url_prefix``, ``static_handler_class``,
    and ``static_handler_args`` settings.

    To map an additional path to this handler for a static data directory
    you would add a line to your application like::

        application = web.Application([
            (r"/content/(.*)", web.StaticFileHandler, {"path": "/var/www"}),
        ])

    The handler constructor requires a ``path`` argument, which specifies the
    local root directory of the content to be served.

    Note that a capture group in the regex is required to parse the value for
    the ``path`` argument to the get() method (different than the constructor
    argument above); see `URLSpec` for details.

    To maximize the effectiveness of browser caching, this class supports
    versioned urls (by default using the argument ``?v=``).  If a version
    is given, we instruct the browser to cache this file indefinitely.
    `make_static_url` (also available as `RequestHandler.static_url`) can
    be used to construct a versioned url.

    This handler is intended primarily for use in development and light-duty
    file serving; for heavy traffic it will be more efficient to use
    a dedicated static file server (such as nginx or Apache).  We support
    the HTTP ``Accept-Ranges`` mechanism to return partial content (because
    some browsers require this functionality to be present to seek in
    HTML5 audio or video), but this handler should not be used with
    files that are too large to fit comfortably in memory.

    **Subclassing notes**

    This class is designed to be extensible by subclassing, but because
    of the way static urls are generated with class methods rather than
    instance methods, the inheritance patterns are somewhat unusual.
    Be sure to use the ``@classmethod`` decorator when overriding a
    class method.  Instance methods may use the attributes ``self.path``
    ``self.absolute_path``, and ``self.modified``.

    To change the way static urls are generated (e.g. to match the behavior
    of another server or CDN), override `make_static_url`, `parse_url_path`,
    `get_cache_time`, and/or `get_version`.

    To replace all interaction with the filesystem (e.g. to serve
    static content from a database), override `get_content`,
    `get_content_size`, `get_modified_time`, `get_absolute_path`, and
    `validate_absolute_path`.

    .. versionchanged:: 3.1
       Many of the methods for subclasses were added in Tornado 3.1.
    """
    CACHE_MAX_AGE = 86400 * 365 * 10  # 10 years

    _static_hashes = {}
    _lock = threading.Lock()  # protects _static_hashes

    def initialize(self, path, default_filename=None):
        self.root = path
        self.default_filename = default_filename

    @classmethod
    def reset(cls):
        with cls._lock:
            cls._static_hashes = {}

    def head(self, path):
        self.get(path, include_body=False)

    def get(self, path, include_body=True):
        # Set up our path instance variables.
        self.path = self.parse_url_path(path)
        del path  # make sure we don't refer to path instead of self.path again
        absolute_path = self.get_absolute_path(self.root, self.path)
        self.absolute_path = self.validate_absolute_path(
            self.root, absolute_path)
        if self.absolute_path is None:
            return

        self.modified = self.get_modified_time()
        self.set_headers()

        if self.should_return_304():
            self.set_status(304)
            return

        request_range = None
        range_header = self.request.headers.get("Range")
        if range_header:
            # As per RFC 2616 14.16, if an invalid Range header is specified,
            # the request will be treated as if the header didn't exist.
            request_range = httputil._parse_request_range(range_header)

        if request_range:
            start, end = request_range
            size = self.get_content_size()
            if (start is not None and start >= size) or end == 0:
                # As per RFC 2616 14.35.1, a range is not satisfiable only: if
                # the first requested byte is equal to or greater than the
                # content, or when a suffix with length 0 is specified
                self.set_status(416)  # Range Not Satisfiable
                self.set_header("Content-Type", "text/plain")
                self.set_header("Content-Range", "bytes */%s" %(size, ))
                return
            if start is not None and start < 0:
                start += size
            if end is not None and end > size:
                # Clients sometimes blindly use a large range to limit their
                # download size; cap the endpoint at the actual file size.
                end = size
            # Note: only return HTTP 206 if less than the entire range has been
            # requested. Not only is this semantically correct, but Chrome
            # refuses to play audio if it gets an HTTP 206 in response to
            # ``Range: bytes=0-``.
            if size != (end or size) - (start or 0):
                self.set_status(206)  # Partial Content
                self.set_header("Content-Range",
                                httputil._get_content_range(start, end, size))
        else:
            start = end = None
        content = self.get_content(self.absolute_path, start, end)
        if isinstance(content, bytes_type):
            content = [content]
        content_length = 0
        for chunk in content:
            if include_body:
                self.write(chunk)
            else:
                content_length += len(chunk)
        if not include_body:
            assert self.request.method == "HEAD"
            self.set_header("Content-Length", content_length)

    def compute_etag(self):
        """Sets the ``Etag`` header based on static url version.

        This allows efficient ``If-None-Match`` checks against cached
        versions, and sends the correct ``Etag`` for a partial response
        (i.e. the same ``Etag`` as the full file).

        .. versionadded:: 3.1
        """
        version_hash = self._get_cached_version(self.absolute_path)
        if not version_hash:
            return None
        return '"%s"' % (version_hash, )

    def set_headers(self):
        """Sets the content and caching headers on the response.

        .. versionadded:: 3.1
        """
        self.set_header("Accept-Ranges", "bytes")
        self.set_etag_header()

        if self.modified is not None:
            self.set_header("Last-Modified", self.modified)

        content_type = self.get_content_type()
        if content_type:
            self.set_header("Content-Type", content_type)

        cache_time = self.get_cache_time(self.path, self.modified, content_type)
        if cache_time > 0:
            self.set_header("Expires", datetime.datetime.utcnow() +
                            datetime.timedelta(seconds=cache_time))
            self.set_header("Cache-Control", "max-age=" + str(cache_time))

        self.set_extra_headers(self.path)

    def should_return_304(self):
        """Returns True if the headers indicate that we should return 304.

        .. versionadded:: 3.1
        """
        if self.check_etag_header():
            return True

        # Check the If-Modified-Since, and don't send the result if the
        # content has not been modified
        ims_value = self.request.headers.get("If-Modified-Since")
        if ims_value is not None:
            date_tuple = email.utils.parsedate(ims_value)
            if date_tuple is not None:
                if_since = datetime.datetime(*date_tuple[:6])
                if if_since >= self.modified:
                    return True

        return False

    @classmethod
    def get_absolute_path(cls, root, path):
        """Returns the absolute location of ``path`` relative to ``root``.

        ``root`` is the path configured for this `StaticFileHandler`
        (in most cases the ``static_path`` `Application` setting).

        This class method may be overridden in subclasses.  By default
        it returns a filesystem path, but other strings may be used
        as long as they are unique and understood by the subclass's
        overridden `get_content`.

        .. versionadded:: 3.1
        """
        abspath = os.path.abspath(os.path.join(root, path))
        return abspath

    def validate_absolute_path(self, root, absolute_path):
        """Validate and return the absolute path.

        ``root`` is the configured path for the `StaticFileHandler`,
        and ``path`` is the result of `get_absolute_path`

        This is an instance method called during request processing,
        so it may raise `HTTPError` or use methods like
        `RequestHandler.redirect` (return None after redirecting to
        halt further processing).  This is where 404 errors for missing files
        are generated.

        This method may modify the path before returning it, but note that
        any such modifications will not be understood by `make_static_url`.

        In instance methods, this method's result is available as
        ``self.absolute_path``.

        .. versionadded:: 3.1
        """
        root = os.path.abspath(root)
        # os.path.abspath strips a trailing /
        # it needs to be temporarily added back for requests to root/
        if not (absolute_path + os.path.sep).startswith(root):
            raise HTTPError(403, "%s is not in root static directory",
                            self.path)
        if (os.path.isdir(absolute_path) and
                self.default_filename is not None):
            # need to look at the request.path here for when path is empty
            # but there is some prefix to the path that was already
            # trimmed by the routing
            if not self.request.path.endswith("/"):
                self.redirect(self.request.path + "/", permanent=True)
                return
            absolute_path = os.path.join(absolute_path, self.default_filename)
        if not os.path.exists(absolute_path):
            raise HTTPError(404)
        if not os.path.isfile(absolute_path):
            raise HTTPError(403, "%s is not a file", self.path)
        return absolute_path

    @classmethod
    def get_content(cls, abspath, start=None, end=None):
        """Retrieve the content of the requested resource which is located
        at the given absolute path.

        This class method may be overridden by subclasses.  Note that its
        signature is different from other overridable class methods
        (no ``settings`` argument); this is deliberate to ensure that
        ``abspath`` is able to stand on its own as a cache key.

        This method should either return a byte string or an iterator
        of byte strings.  The latter is preferred for large files
        as it helps reduce memory fragmentation.

        .. versionadded:: 3.1
        """
        with open(abspath, "rb") as file:
            if start is not None:
                file.seek(start)
            if end is not None:
                remaining = end - (start or 0)
            else:
                remaining = None
            while True:
                chunk_size = 64 * 1024
                if remaining is not None and remaining < chunk_size:
                    chunk_size = remaining
                chunk = file.read(chunk_size)
                if chunk:
                    if remaining is not None:
                        remaining -= len(chunk)
                    yield chunk
                else:
                    if remaining is not None:
                        assert remaining == 0
                    return

    @classmethod
    def get_content_version(cls, abspath):
        """Returns a version string for the resource at the given path.

        This class method may be overridden by subclasses.  The
        default implementation is a hash of the file's contents.

        .. versionadded:: 3.1
        """
        data = cls.get_content(abspath)
        hasher = hashlib.md5()
        if isinstance(data, bytes_type):
            hasher.update(data)
        else:
            for chunk in data:
                hasher.update(chunk)
        return hasher.hexdigest()

    def _stat(self):
        if not hasattr(self, '_stat_result'):
            self._stat_result = os.stat(self.absolute_path)
        return self._stat_result

    def get_content_size(self):
        """Retrieve the total size of the resource at the given path.

        This method may be overridden by subclasses. It will only
        be called if a partial result is requested from `get_content`

        .. versionadded:: 3.1
        """
        stat_result = self._stat()
        return stat_result[stat.ST_SIZE]

    def get_modified_time(self):
        """Returns the time that ``self.absolute_path`` was last modified.

        May be overridden in subclasses.  Should return a `~datetime.datetime`
        object or None.

        .. versionadded:: 3.1
        """
        stat_result = self._stat()
        modified = datetime.datetime.utcfromtimestamp(stat_result[stat.ST_MTIME])
        return modified

    def get_content_type(self):
        """Returns the ``Content-Type`` header to be used for this request.

        .. versionadded:: 3.1
        """
        mime_type, encoding = mimetypes.guess_type(self.absolute_path)
        return mime_type

    def set_extra_headers(self, path):
        """For subclass to add extra headers to the response"""
        pass

    def get_cache_time(self, path, modified, mime_type):
        """Override to customize cache control behavior.

        Return a positive number of seconds to make the result
        cacheable for that amount of time or 0 to mark resource as
        cacheable for an unspecified amount of time (subject to
        browser heuristics).

        By default returns cache expiry of 10 years for resources requested
        with ``v`` argument.
        """
        return self.CACHE_MAX_AGE if "v" in self.request.arguments else 0

    @classmethod
    def make_static_url(cls, settings, path, include_version=True):
        """Constructs a versioned url for the given path.

        This method may be overridden in subclasses (but note that it
        is a class method rather than an instance method).  Subclasses
        are only required to implement the signature
        ``make_static_url(cls, settings, path)``; other keyword
        arguments may be passed through `~RequestHandler.static_url`
        but are not standard.

        ``settings`` is the `Application.settings` dictionary.  ``path``
        is the static path being requested.  The url returned should be
        relative to the current host.

        ``include_version`` determines whether the generated URL should
        include the query string containing the version hash of the
        file corresponding to the given ``path``.

        """
        url = settings.get('static_url_prefix', '/static/') + path
        if not include_version:
            return url

        version_hash = cls.get_version(settings, path)
        if not version_hash:
            return url

        return '%s?v=%s' % (url, version_hash)

    def parse_url_path(self, url_path):
        """Converts a static URL path into a filesystem path.

        ``url_path`` is the path component of the URL with
        ``static_url_prefix`` removed.  The return value should be
        filesystem path relative to ``static_path``.

        This is the inverse of `make_static_url`.
        """
        if os.path.sep != "/":
            url_path = url_path.replace("/", os.path.sep)
        return url_path

    @classmethod
    def get_version(cls, settings, path):
        """Generate the version string to be used in static URLs.

        ``settings`` is the `Application.settings` dictionary and ``path``
        is the relative location of the requested asset on the filesystem.
        The returned value should be a string, or ``None`` if no version
        could be determined.

        .. versionchanged:: 3.1
           This method was previously recommended for subclasses to override;
           `get_content_version` is now preferred as it allows the base
           class to handle caching of the result.
        """
        abs_path = cls.get_absolute_path(settings['static_path'], path)
        return cls._get_cached_version(abs_path)

    @classmethod
    def _get_cached_version(cls, abs_path):
        with cls._lock:
            hashes = cls._static_hashes
            if abs_path not in hashes:
                try:
                    hashes[abs_path] = cls.get_content_version(abs_path)
                except Exception:
                    gen_log.error("Could not open static file %r", abs_path)
                    hashes[abs_path] = None
            hsh = hashes.get(abs_path)
            if hsh:
                return hsh
        return None


class FallbackHandler(RequestHandler):
    """A `RequestHandler` that wraps another HTTP server callback.

    The fallback is a callable object that accepts an
    `~.httpserver.HTTPRequest`, such as an `Application` or
    `tornado.wsgi.WSGIContainer`.  This is most useful to use both
    Tornado ``RequestHandlers`` and WSGI in the same server.  Typical
    usage::

        wsgi_app = tornado.wsgi.WSGIContainer(
            django.core.handlers.wsgi.WSGIHandler())
        application = tornado.web.Application([
            (r"/foo", FooHandler),
            (r".*", FallbackHandler, dict(fallback=wsgi_app),
        ])
    """
    def initialize(self, fallback):
        self.fallback = fallback

    def prepare(self):
        self.fallback(self.request)
        self._finished = True


class OutputTransform(object):
    """A transform modifies the result of an HTTP request (e.g., GZip encoding)

    A new transform instance is created for every request. See the
    ChunkedTransferEncoding example below if you want to implement a
    new Transform.
    """
    def __init__(self, request):
        pass

    def transform_first_chunk(self, status_code, headers, chunk, finishing):
        return status_code, headers, chunk

    def transform_chunk(self, chunk, finishing):
        return chunk


class GZipContentEncoding(OutputTransform):
    """Applies the gzip content encoding to the response.

    See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11
    """
    CONTENT_TYPES = set([
        "text/plain", "text/html", "text/css", "text/xml", "application/javascript",
        "application/x-javascript", "application/xml", "application/atom+xml",
        "text/javascript", "application/json", "application/xhtml+xml"])
    MIN_LENGTH = 5

    def __init__(self, request):
        self._gzipping = request.supports_http_1_1() and \
            "gzip" in request.headers.get("Accept-Encoding", "")

    def transform_first_chunk(self, status_code, headers, chunk, finishing):
        if 'Vary' in headers:
            headers['Vary'] += b', Accept-Encoding'
        else:
            headers['Vary'] = b'Accept-Encoding'
        if self._gzipping:
            ctype = _unicode(headers.get("Content-Type", "")).split(";")[0]
            self._gzipping = (ctype in self.CONTENT_TYPES) and \
                (not finishing or len(chunk) >= self.MIN_LENGTH) and \
                (finishing or "Content-Length" not in headers) and \
                ("Content-Encoding" not in headers)
        if self._gzipping:
            headers["Content-Encoding"] = "gzip"
            self._gzip_value = BytesIO()
            self._gzip_file = gzip.GzipFile(mode="w", fileobj=self._gzip_value)
            chunk = self.transform_chunk(chunk, finishing)
            if "Content-Length" in headers:
                headers["Content-Length"] = str(len(chunk))
        return status_code, headers, chunk

    def transform_chunk(self, chunk, finishing):
        if self._gzipping:
            self._gzip_file.write(chunk)
            if finishing:
                self._gzip_file.close()
            else:
                self._gzip_file.flush()
            chunk = self._gzip_value.getvalue()
            self._gzip_value.truncate(0)
            self._gzip_value.seek(0)
        return chunk


class ChunkedTransferEncoding(OutputTransform):
    """Applies the chunked transfer encoding to the response.

    See http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.6.1
    """
    def __init__(self, request):
        self._chunking = request.supports_http_1_1()

    def transform_first_chunk(self, status_code, headers, chunk, finishing):
        # 304 responses have no body (not even a zero-length body), and so
        # should not have either Content-Length or Transfer-Encoding headers.
        if self._chunking and status_code != 304:
            # No need to chunk the output if a Content-Length is specified
            if "Content-Length" in headers or "Transfer-Encoding" in headers:
                self._chunking = False
            else:
                headers["Transfer-Encoding"] = "chunked"
                chunk = self.transform_chunk(chunk, finishing)
        return status_code, headers, chunk

    def transform_chunk(self, block, finishing):
        if self._chunking:
            # Don't write out empty chunks because that means END-OF-STREAM
            # with chunked encoding
            if block:
                block = utf8("%x" % len(block)) + b"\r\n" + block + b"\r\n"
            if finishing:
                block += b"0\r\n\r\n"
        return block


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


class UIModule(object):
    """A re-usable, modular UI unit on a page.

    UI modules often execute additional queries, and they can include
    additional CSS and JavaScript that will be included in the output
    page, which is automatically inserted on page render.
    """
    def __init__(self, handler):
        self.handler = handler
        self.request = handler.request
        self.ui = handler.ui
        self.current_user = handler.current_user
        self.locale = handler.locale

    def render(self, *args, **kwargs):
        """Overridden in subclasses to return this module's output."""
        raise NotImplementedError()

    def embedded_javascript(self):
        """Returns a JavaScript string that will be embedded in the page."""
        return None

    def javascript_files(self):
        """Returns a list of JavaScript files required by this module."""
        return None

    def embedded_css(self):
        """Returns a CSS string that will be embedded in the page."""
        return None

    def css_files(self):
        """Returns a list of CSS files required by this module."""
        return None

    def html_head(self):
        """Returns a CSS string that will be put in the <head/> element"""
        return None

    def html_body(self):
        """Returns an HTML string that will be put in the <body/> element"""
        return None

    def render_string(self, path, **kwargs):
        """Renders a template and returns it as a string."""
        return self.handler.render_string(path, **kwargs)


class _linkify(UIModule):
    def render(self, text, **kwargs):
        return escape.linkify(text, **kwargs)


class _xsrf_form_html(UIModule):
    def render(self):
        return self.handler.xsrf_form_html()


class TemplateModule(UIModule):
    """UIModule that simply renders the given template.

    {% module Template("foo.html") %} is similar to {% include "foo.html" %},
    but the module version gets its own namespace (with kwargs passed to
    Template()) instead of inheriting the outer template's namespace.

    Templates rendered through this module also get access to UIModule's
    automatic javascript/css features.  Simply call set_resources
    inside the template and give it keyword arguments corresponding to
    the methods on UIModule: {{ set_resources(js_files=static_url("my.js")) }}
    Note that these resources are output once per template file, not once
    per instantiation of the template, so they must not depend on
    any arguments to the template.
    """
    def __init__(self, handler):
        super(TemplateModule, self).__init__(handler)
        # keep resources in both a list and a dict to preserve order
        self._resource_list = []
        self._resource_dict = {}

    def render(self, path, **kwargs):
        def set_resources(**kwargs):
            if path not in self._resource_dict:
                self._resource_list.append(kwargs)
                self._resource_dict[path] = kwargs
            else:
                if self._resource_dict[path] != kwargs:
                    raise ValueError("set_resources called with different "
                                     "resources for the same template")
            return ""
        return self.render_string(path, set_resources=set_resources,
                                  **kwargs)

    def _get_resources(self, key):
        return (r[key] for r in self._resource_list if key in r)

    def embedded_javascript(self):
        return "\n".join(self._get_resources("embedded_javascript"))

    def javascript_files(self):
        result = []
        for f in self._get_resources("javascript_files"):
            if isinstance(f, (unicode_type, bytes_type)):
                result.append(f)
            else:
                result.extend(f)
        return result

    def embedded_css(self):
        return "\n".join(self._get_resources("embedded_css"))

    def css_files(self):
        result = []
        for f in self._get_resources("css_files"):
            if isinstance(f, (unicode_type, bytes_type)):
                result.append(f)
            else:
                result.extend(f)
        return result

    def html_head(self):
        return "".join(self._get_resources("html_head"))

    def html_body(self):
        return "".join(self._get_resources("html_body"))


class _UIModuleNamespace(object):
    """Lazy namespace which creates UIModule proxies bound to a handler."""
    def __init__(self, handler, ui_modules):
        self.handler = handler
        self.ui_modules = ui_modules

    def __getitem__(self, key):
        return self.handler._ui_module(key, self.ui_modules[key])

    def __getattr__(self, key):
        try:
            return self[key]
        except KeyError as e:
            raise AttributeError(str(e))


class URLSpec(object):
    """Specifies mappings between URLs and handlers."""
    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()

    def __repr__(self):
        return '%s(%r, %s, kwargs=%r, name=%r)' % \
            (self.__class__.__name__, self.regex.pattern,
             self.handler_class, self.kwargs, self.name)

    def _find_groups(self):
        """Returns a tuple (reverse string, group count) for a url.

        For example: Given the url pattern /([0-9]{4})/([a-z-]+)/, this method
        would return ('/%s/%s/', 2).
        """
        pattern = self.regex.pattern
        if pattern.startswith('^'):
            pattern = pattern[1:]
        if pattern.endswith('$'):
            pattern = pattern[:-1]

        if self.regex.groups != pattern.count('('):
            # The pattern is too complicated for our simplistic matching,
            # so we can't support reversing it.
            return (None, None)

        pieces = []
        for fragment in pattern.split('('):
            if ')' in fragment:
                paren_loc = fragment.index(')')
                if paren_loc >= 0:
                    pieces.append('%s' + fragment[paren_loc + 1:])
            else:
                pieces.append(fragment)

        return (''.join(pieces), self.regex.groups)

    def reverse(self, *args):
        assert self._path is not None, \
            "Cannot reverse url regex " + self.regex.pattern
        assert len(args) == self._group_count, "required number of arguments "\
            "not found"
        if not len(args):
            return self._path
        converted_args = []
        for a in args:
            if not isinstance(a, (unicode_type, bytes_type)):
                a = str(a)
            converted_args.append(escape.url_escape(utf8(a), plus=False))
        return self._path % tuple(converted_args)

url = URLSpec


if hasattr(hmac, 'compare_digest'):  # python 3.3
    _time_independent_equals = hmac.compare_digest
else:
    def _time_independent_equals(a, b):
        if len(a) != len(b):
            return False
        result = 0
        if isinstance(a[0], int):  # python3 byte strings
            for x, y in zip(a, b):
                result |= x ^ y
        else:  # python2
            for x, y in zip(a, b):
                result |= ord(x) ^ ord(y)
        return result == 0


def create_signed_value(secret, name, value):
    timestamp = utf8(str(int(time.time())))
    value = base64.b64encode(utf8(value))
    signature = _create_signature(secret, name, value, timestamp)
    value = b"|".join([value, timestamp, signature])
    return value


def decode_signed_value(secret, name, value, max_age_days=31):
    if not value:
        return None
    parts = utf8(value).split(b"|")
    if len(parts) != 3:
        return None
    signature = _create_signature(secret, name, parts[0], parts[1])
    if not _time_independent_equals(parts[2], signature):
        gen_log.warning("Invalid cookie signature %r", value)
        return None
    timestamp = int(parts[1])
    if timestamp < time.time() - max_age_days * 86400:
        gen_log.warning("Expired cookie %r", value)
        return None
    if timestamp > time.time() + 31 * 86400:
        # _cookie_signature does not hash a delimiter between the
        # parts of the cookie, so an attacker could transfer trailing
        # digits from the payload to the timestamp without altering the
        # signature.  For backwards compatibility, sanity-check timestamp
        # here instead of modifying _cookie_signature.
        gen_log.warning("Cookie timestamp in future; possible tampering %r", value)
        return None
    if parts[1].startswith(b"0"):
        gen_log.warning("Tampered cookie %r", value)
        return None
    try:
        return base64.b64decode(parts[0])
    except Exception:
        return None


def _create_signature(secret, *parts):
    hash = hmac.new(utf8(secret), digestmod=hashlib.sha1)
    for part in parts:
        hash.update(utf8(part))
    return utf8(hash.hexdigest())

```
--- END FILE ---

Please first localize the bug based on the issue statement, and then generate *SEARCH/REPLACE* edits to fix the issue.

Every *SEARCH/REPLACE* edit must use this format:
1. The file path
2. The start of search block: <<<<<<< SEARCH
3. A contiguous chunk of lines to search for in the existing source code
4. The dividing line: =======
5. The lines to replace into the source code
6. The end of the replace block: >>>>>>> REPLACE

Here is an example:

```python
### mathweb/flask/app.py
<<<<<<< SEARCH
from flask import Flask
=======
import math
from flask import Flask
>>>>>>> REPLACE
```
</solution>

Please note that the *SEARCH/REPLACE* edit REQUIRES PROPER INDENTATION. If you would like to add the line '        print(x)', you must fully write that out, with all those spaces before the code!
Wrap each *SEARCH/REPLACE* edit in a code block as shown in the example above. If you have multiple *SEARCH/REPLACE* edits, use a separate code block for each one.
[ISSUE]
**Title:** `current_user` in UI modules is not lazily evaluated

**Description:**
When using `current_user` within UI modules, it is evaluated immediately during the module's initialization rather than being accessed lazily. This premature evaluation can lead to unexpected behavior, such as unnecessary database queries or incorrect user data being loaded before it's needed.

**Example Buggy Code:**
```python
class UserProfileModule(UIModule):
    def render(self):
        user = self.current_user  # This triggers get_current_user immediately
        if user:
            return f"Hello, {user.name}!"
        return "Hello, Guest!"
```

In the above example, accessing `self.current_user` during the `render` method causes the `get_current_user` method to be called immediately, which may not be desirable in all contexts.

**Expected Behavior:**
The `current_user` property should be accessed lazily, meaning `get_current_user` is called only when `current_user` is explicitly accessed within the UI module. This ensures that user data is loaded only when necessary, improving performance and preventing unintended side effects.

**Actual Behavior:**
`current_user` is evaluated eagerly during the initialization of the UI module, leading to premature calls to `get_current_user`. This results in unnecessary processing and potential inconsistencies in user data handling.

[/ISSUE]
{
    "AllHTTPMethodsTest.test_standard_methods": "PASSED",
    "AuthRedirectTest.test_absolute_auth_redirect": "PASSED",
    "AuthRedirectTest.test_relative_auth_redirect": "PASSED",
    "ClearAllCookiesTest.test_clear_all_cookies": "FAILED",
    "ClearHeaderTest.test_clear_header": "PASSED",
    "ConnectionCloseTest.test_connection_close": "PASSED",
    "CookieTest.test_cookie_special_char": "PASSED",
    "CookieTest.test_get_cookie": "PASSED",
    "CookieTest.test_set_cookie": "PASSED",
    "CookieTest.test_set_cookie_domain": "PASSED",
    "CookieTest.test_set_cookie_overwrite": "PASSED",
    "CustomStaticFileTest.test_serve": "PASSED",
    "CustomStaticFileTest.test_static_url": "PASSED",
    "DateHeaderTest.test_date_header": "PASSED",
    "ErrorHandlerXSRFTest.test_404_xsrf": "PASSED",
    "ErrorHandlerXSRFTest.test_error_xsrf": "PASSED",
    "ErrorResponseTest.test_default": "PASSED",
    "ErrorResponseTest.test_failed_write_error": "PASSED",
    "ErrorResponseTest.test_get_error_html": "PASSED",
    "ErrorResponseTest.test_write_error": "PASSED",
    "ExceptionHandlerTest.test_http_error": "PASSED",
    "ExceptionHandlerTest.test_known_error": "PASSED",
    "ExceptionHandlerTest.test_unknown_error": "PASSED",
    "FinishInPrepareTest.test_finish_in_prepare": "PASSED",
    "GetArgumentErrorTest.test_catch_error": "PASSED",
    "GetCurrentUserTest.test_get_current_user_from_ui_module_is_lazy": "PASSED",
    "GetCurrentUserTest.test_get_current_user_from_ui_module_works": "PASSED",
    "GetCurrentUserTest.test_get_current_user_works": "PASSED",
    "GzipTestCase.test_gzip": "PASSED",
    "GzipTestCase.test_gzip_not_requested": "PASSED",
    "GzipTestCase.test_vary_already_present": "PASSED",
    "Header304Test.test_304_headers": "PASSED",
    "HostMatchingTest.test_host_matching": "PASSED",
    "MultipleExceptionTest.test_multi_exception": "PASSED",
    "NamedURLSpecGroupsTest.test_named_urlspec_groups": "PASSED",
    "NonWSGIWebTests.test_empty_flush": "PASSED",
    "NonWSGIWebTests.test_flow_control": "PASSED",
    "PatchMethodTest.test_other": "PASSED",
    "PatchMethodTest.test_patch": "PASSED",
    "PathArgsInPrepareTest.test_kw": "PASSED",
    "PathArgsInPrepareTest.test_pos": "PASSED",
    "RaiseWithReasonTest.test_httperror_str": "PASSED",
    "RaiseWithReasonTest.test_raise_with_reason": "PASSED",
    "RequestEncodingTest.test_group_encoding": "PASSED",
    "RequestEncodingTest.test_group_question_mark": "PASSED",
    "RequestEncodingTest.test_slashes": "PASSED",
    "SecureCookieTest.test_arbitrary_bytes": "PASSED",
    "SecureCookieTest.test_cookie_tampering_future_timestamp": "PASSED",
    "SecureCookieTest.test_round_trip": "PASSED",
    "SetCurrentUserTest.test_set_current_user": "PASSED",
    "StaticDefaultFilenameTest.test_static_default_filename": "FAILED",
    "StaticDefaultFilenameTest.test_static_default_redirect": "FAILED",
    "StaticFileTest.test_absolute_static_url": "FAILED",
    "StaticFileTest.test_absolute_version_exclusion": "PASSED",
    "StaticFileTest.test_include_host_override": "PASSED",
    "StaticFileTest.test_relative_version_exclusion": "PASSED",
    "StaticFileTest.test_static_304_if_modified_since": "ERROR",
    "StaticFileTest.test_static_304_if_none_match": "ERROR",
    "StaticFileTest.test_static_404": "PASSED",
    "StaticFileTest.test_static_etag": "FAILED",
    "StaticFileTest.test_static_files": "FAILED",
    "StaticFileTest.test_static_head": "FAILED",
    "StaticFileTest.test_static_head_range": "FAILED",
    "StaticFileTest.test_static_if_modified_since_pre_epoch": "FAILED",
    "StaticFileTest.test_static_if_modified_since_time_zone": "ERROR",
    "StaticFileTest.test_static_invalid_range": "FAILED",
    "StaticFileTest.test_static_range_if_none_match": "FAILED",
    "StaticFileTest.test_static_unsatisfiable_range_invalid_start": "FAILED",
    "StaticFileTest.test_static_unsatisfiable_range_zero_suffix": "FAILED",
    "StaticFileTest.test_static_url": "FAILED",
    "StaticFileTest.test_static_with_range": "FAILED",
    "StaticFileTest.test_static_with_range_end_edge": "FAILED",
    "StaticFileTest.test_static_with_range_full_file": "FAILED",
    "StaticFileTest.test_static_with_range_full_past_end": "FAILED",
    "StaticFileTest.test_static_with_range_neg_end": "FAILED",
    "StaticFileTest.test_static_with_range_partial_past_end": "FAILED",
    "StaticFileWithPathTest.test_serve": "FAILED",
    "StatusReasonTest.test_status": "PASSED",
    "UIMethodUIModuleTest.test_ui_method": "PASSED",
    "UnimplementedHTTPMethodsTest.test_unimplemented_standard_methods": "PASSED",
    "UnimplementedNonStandardMethodsTest.test_unimplemented_other": "PASSED",
    "UnimplementedNonStandardMethodsTest.test_unimplemented_patch": "PASSED",
    "WSGISafeWebTest.test_decode_argument": "PASSED",
    "WSGISafeWebTest.test_decode_argument_plus": "PASSED",
    "WSGISafeWebTest.test_get_argument": "PASSED",
    "WSGISafeWebTest.test_header_injection": "PASSED",
    "WSGISafeWebTest.test_multi_header": "PASSED",
    "WSGISafeWebTest.test_no_gzip": "PASSED",
    "WSGISafeWebTest.test_optional_path": "PASSED",
    "WSGISafeWebTest.test_redirect": "PASSED",
    "WSGISafeWebTest.test_reverse_url": "PASSED",
    "WSGISafeWebTest.test_types": "PASSED",
    "WSGISafeWebTest.test_uimodule_resources": "PASSED",
    "WSGISafeWebTest.test_uimodule_unescaped": "PASSED"
}
diff --git a/tornado/web.py b/tornado/web.py
index 63f5514c..e09dda9b 100644
--- a/tornado/web.py
+++ b/tornado/web.py
@@ -2309,9 +2309,12 @@ class UIModule(object):
         self.handler = handler
         self.request = handler.request
         self.ui = handler.ui
-        self.current_user = handler.current_user
         self.locale = handler.locale
 
+    @property
+    def current_user(self):
+        return self.handler.current_user
+
     def render(self, *args, **kwargs):
         """Overridden in subclasses to return this module's output."""
         raise NotImplementedError()
 

{"tornado/web.py": "#!/usr/bin/env python\n#\n# Copyright 2009 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"``tornado.web`` provides a simple web framework with asynchronous\nfeatures that allow it to scale to large numbers of open connections,\nmaking it ideal for `long polling\n<http://en.wikipedia.org/wiki/Push_technology#Long_polling>`_.\n\nHere is a simple \"Hello, world\" example app::\n\n    import tornado.ioloop\n    import tornado.web\n\n    class MainHandler(tornado.web.RequestHandler):\n        def get(self):\n            self.write(\"Hello, world\")\n\n    if __name__ == \"__main__\":\n        application = tornado.web.Application([\n            (r\"/\", MainHandler),\n        ])\n        application.listen(8888)\n        tornado.ioloop.IOLoop.instance().start()\n\nSee the :doc:`Tornado overview <overview>` for more details and a good getting\nstarted guide.\n\nThread-safety notes\n-------------------\n\nIn general, methods on `RequestHandler` and elsewhere in Tornado are\nnot thread-safe.  In particular, methods such as\n`~RequestHandler.write()`, `~RequestHandler.finish()`, and\n`~RequestHandler.flush()` must only be called from the main thread.  If\nyou use multiple threads it is important to use `.IOLoop.add_callback`\nto transfer control back to the main thread before finishing the\nrequest.\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function, with_statement\n\n\nimport base64\nimport binascii\nimport datetime\nimport email.utils\nimport functools\nimport gzip\nimport hashlib\nimport hmac\nimport mimetypes\nimport numbers\nimport os.path\nimport re\nimport stat\nimport sys\nimport threading\nimport time\nimport tornado\nimport traceback\nimport types\nimport uuid\n\nfrom tornado.concurrent import Future\nfrom tornado import escape\nfrom tornado import httputil\nfrom tornado import locale\nfrom tornado.log import access_log, app_log, gen_log\nfrom tornado import stack_context\nfrom tornado import template\nfrom tornado.escape import utf8, _unicode\nfrom tornado.util import bytes_type, import_object, ObjectDict, raise_exc_info, unicode_type\n\ntry:\n    from io import BytesIO  # python 3\nexcept ImportError:\n    from cStringIO import StringIO as BytesIO  # python 2\n\ntry:\n    import Cookie  # py2\nexcept ImportError:\n    import http.cookies as Cookie  # py3\n\ntry:\n    import urlparse  # py2\nexcept ImportError:\n    import urllib.parse as urlparse  # py3\n\ntry:\n    from urllib import urlencode  # py2\nexcept ImportError:\n    from urllib.parse import urlencode  # py3\n\n\nclass RequestHandler(object):\n    \"\"\"Subclass this class and define `get()` or `post()` to make a handler.\n\n    If you want to support more methods than the standard GET/HEAD/POST, you\n    should override the class variable ``SUPPORTED_METHODS`` in your\n    `RequestHandler` subclass.\n    \"\"\"\n    SUPPORTED_METHODS = (\"GET\", \"HEAD\", \"POST\", \"DELETE\", \"PATCH\", \"PUT\",\n                         \"OPTIONS\")\n\n    _template_loaders = {}  # {path: template.BaseLoader}\n    _template_loader_lock = threading.Lock()\n    _remove_control_chars_regex = re.compile(r\"[\\x00-\\x08\\x0e-\\x1f]\")\n\n    def __init__(self, application, request, **kwargs):\n        super(RequestHandler, self).__init__()\n\n        self.application = application\n        self.request = request\n        self._headers_written = False\n        self._finished = False\n        self._auto_finish = True\n        self._transforms = None  # will be set in _execute\n        self.path_args = None\n        self.path_kwargs = None\n        self.ui = ObjectDict((n, self._ui_method(m)) for n, m in\n                             application.ui_methods.items())\n        # UIModules are available as both `modules` and `_tt_modules` in the\n        # template namespace.  Historically only `modules` was available\n        # but could be clobbered by user additions to the namespace.\n        # The template {% module %} directive looks in `_tt_modules` to avoid\n        # possible conflicts.\n        self.ui[\"_tt_modules\"] = _UIModuleNamespace(self,\n                                                    application.ui_modules)\n        self.ui[\"modules\"] = self.ui[\"_tt_modules\"]\n        self.clear()\n        # Check since connection is not available in WSGI\n        if getattr(self.request, \"connection\", None):\n            self.request.connection.set_close_callback(\n                self.on_connection_close)\n        self.initialize(**kwargs)\n\n    def initialize(self):\n        \"\"\"Hook for subclass initialization.\n\n        A dictionary passed as the third argument of a url spec will be\n        supplied as keyword arguments to initialize().\n\n        Example::\n\n            class ProfileHandler(RequestHandler):\n                def initialize(self, database):\n                    self.database = database\n\n                def get(self, username):\n                    ...\n\n            app = Application([\n                (r'/user/(.*)', ProfileHandler, dict(database=database)),\n                ])\n        \"\"\"\n        pass\n\n    @property\n    def settings(self):\n        \"\"\"An alias for `self.application.settings <Application.settings>`.\"\"\"\n        return self.application.settings\n\n    def head(self, *args, **kwargs):\n        raise HTTPError(405)\n\n    def get(self, *args, **kwargs):\n        raise HTTPError(405)\n\n    def post(self, *args, **kwargs):\n        raise HTTPError(405)\n\n    def delete(self, *args, **kwargs):\n        raise HTTPError(405)\n\n    def patch(self, *args, **kwargs):\n        raise HTTPError(405)\n\n    def put(self, *args, **kwargs):\n        raise HTTPError(405)\n\n    def options(self, *args, **kwargs):\n        raise HTTPError(405)\n\n    def prepare(self):\n        \"\"\"Called at the beginning of a request before  `get`/`post`/etc.\n\n        Override this method to perform common initialization regardless\n        of the request method.\n\n        Asynchronous support: Decorate this method with `.gen.coroutine`\n        or `.return_future` to make it asynchronous (the\n        `asynchronous` decorator cannot be used on `prepare`).\n        If this method returns a `.Future` execution will not proceed\n        until the `.Future` is done.\n\n        .. versionadded:: 3.1\n           Asynchronous support.\n        \"\"\"\n        pass\n\n    def on_finish(self):\n        \"\"\"Called after the end of a request.\n\n        Override this method to perform cleanup, logging, etc.\n        This method is a counterpart to `prepare`.  ``on_finish`` may\n        not produce any output, as it is called after the response\n        has been sent to the client.\n        \"\"\"\n        pass\n\n    def on_connection_close(self):\n        \"\"\"Called in async handlers if the client closed the connection.\n\n        Override this to clean up resources associated with\n        long-lived connections.  Note that this method is called only if\n        the connection was closed during asynchronous processing; if you\n        need to do cleanup after every request override `on_finish`\n        instead.\n\n        Proxies may keep a connection open for a time (perhaps\n        indefinitely) after the client has gone away, so this method\n        may not be called promptly after the end user closes their\n        connection.\n        \"\"\"\n        pass\n\n    def clear(self):\n        \"\"\"Resets all headers and content for this response.\"\"\"\n        self._headers = httputil.HTTPHeaders({\n            \"Server\": \"TornadoServer/%s\" % tornado.version,\n            \"Content-Type\": \"text/html; charset=UTF-8\",\n            \"Date\": httputil.format_timestamp(time.time()),\n        })\n        self.set_default_headers()\n        if (not self.request.supports_http_1_1() and\n            getattr(self.request, 'connection', None) and\n                not self.request.connection.no_keep_alive):\n            conn_header = self.request.headers.get(\"Connection\")\n            if conn_header and (conn_header.lower() == \"keep-alive\"):\n                self.set_header(\"Connection\", \"Keep-Alive\")\n        self._write_buffer = []\n        self._status_code = 200\n        self._reason = httputil.responses[200]\n\n    def set_default_headers(self):\n        \"\"\"Override this to set HTTP headers at the beginning of the request.\n\n        For example, this is the place to set a custom ``Server`` header.\n        Note that setting such headers in the normal flow of request\n        processing may not do what you want, since headers may be reset\n        during error handling.\n        \"\"\"\n        pass\n\n    def set_status(self, status_code, reason=None):\n        \"\"\"Sets the status code for our response.\n\n        :arg int status_code: Response status code. If ``reason`` is ``None``,\n            it must be present in `httplib.responses <http.client.responses>`.\n        :arg string reason: Human-readable reason phrase describing the status\n            code. If ``None``, it will be filled in from\n            `httplib.responses <http.client.responses>`.\n        \"\"\"\n        self._status_code = status_code\n        if reason is not None:\n            self._reason = escape.native_str(reason)\n        else:\n            try:\n                self._reason = httputil.responses[status_code]\n            except KeyError:\n                raise ValueError(\"unknown status code %d\", status_code)\n\n    def get_status(self):\n        \"\"\"Returns the status code for our response.\"\"\"\n        return self._status_code\n\n    def set_header(self, name, value):\n        \"\"\"Sets the given response header name and value.\n\n        If a datetime is given, we automatically format it according to the\n        HTTP specification. If the value is not a string, we convert it to\n        a string. All header values are then encoded as UTF-8.\n        \"\"\"\n        self._headers[name] = self._convert_header_value(value)\n\n    def add_header(self, name, value):\n        \"\"\"Adds the given response header and value.\n\n        Unlike `set_header`, `add_header` may be called multiple times\n        to return multiple values for the same header.\n        \"\"\"\n        self._headers.add(name, self._convert_header_value(value))\n\n    def clear_header(self, name):\n        \"\"\"Clears an outgoing header, undoing a previous `set_header` call.\n\n        Note that this method does not apply to multi-valued headers\n        set by `add_header`.\n        \"\"\"\n        if name in self._headers:\n            del self._headers[name]\n\n    _INVALID_HEADER_CHAR_RE = re.compile(br\"[\\x00-\\x1f]\")\n\n    def _convert_header_value(self, value):\n        if isinstance(value, bytes_type):\n            pass\n        elif isinstance(value, unicode_type):\n            value = value.encode('utf-8')\n        elif isinstance(value, numbers.Integral):\n            # return immediately since we know the converted value will be safe\n            return str(value)\n        elif isinstance(value, datetime.datetime):\n            return httputil.format_timestamp(value)\n        else:\n            raise TypeError(\"Unsupported header value %r\" % value)\n        # If \\n is allowed into the header, it is possible to inject\n        # additional headers or split the request. Also cap length to\n        # prevent obviously erroneous values.\n        if (len(value) > 4000 or\n                RequestHandler._INVALID_HEADER_CHAR_RE.search(value)):\n            raise ValueError(\"Unsafe header value %r\", value)\n        return value\n\n    _ARG_DEFAULT = []\n\n    def get_argument(self, name, default=_ARG_DEFAULT, strip=True):\n        \"\"\"Returns the value of the argument with the given name.\n\n        If default is not provided, the argument is considered to be\n        required, and we raise a `MissingArgumentError` if it is missing.\n\n        If the argument appears in the url more than once, we return the\n        last value.\n\n        The returned value is always unicode.\n        \"\"\"\n        args = self.get_arguments(name, strip=strip)\n        if not args:\n            if default is self._ARG_DEFAULT:\n                raise MissingArgumentError(name)\n            return default\n        return args[-1]\n\n    def get_arguments(self, name, strip=True):\n        \"\"\"Returns a list of the arguments with the given name.\n\n        If the argument is not present, returns an empty list.\n\n        The returned values are always unicode.\n        \"\"\"\n\n        values = []\n        for v in self.request.arguments.get(name, []):\n            v = self.decode_argument(v, name=name)\n            if isinstance(v, unicode_type):\n                # Get rid of any weird control chars (unless decoding gave\n                # us bytes, in which case leave it alone)\n                v = RequestHandler._remove_control_chars_regex.sub(\" \", v)\n            if strip:\n                v = v.strip()\n            values.append(v)\n        return values\n\n    def decode_argument(self, value, name=None):\n        \"\"\"Decodes an argument from the request.\n\n        The argument has been percent-decoded and is now a byte string.\n        By default, this method decodes the argument as utf-8 and returns\n        a unicode string, but this may be overridden in subclasses.\n\n        This method is used as a filter for both `get_argument()` and for\n        values extracted from the url and passed to `get()`/`post()`/etc.\n\n        The name of the argument is provided if known, but may be None\n        (e.g. for unnamed groups in the url regex).\n        \"\"\"\n        return _unicode(value)\n\n    @property\n    def cookies(self):\n        \"\"\"An alias for `self.request.cookies <.httpserver.HTTPRequest.cookies>`.\"\"\"\n        return self.request.cookies\n\n    def get_cookie(self, name, default=None):\n        \"\"\"Gets the value of the cookie with the given name, else default.\"\"\"\n        if self.request.cookies is not None and name in self.request.cookies:\n            return self.request.cookies[name].value\n        return default\n\n    def set_cookie(self, name, value, domain=None, expires=None, path=\"/\",\n                   expires_days=None, **kwargs):\n        \"\"\"Sets the given cookie name/value with the given options.\n\n        Additional keyword arguments are set on the Cookie.Morsel\n        directly.\n        See http://docs.python.org/library/cookie.html#morsel-objects\n        for available attributes.\n        \"\"\"\n        # The cookie library only accepts type str, in both python 2 and 3\n        name = escape.native_str(name)\n        value = escape.native_str(value)\n        if re.search(r\"[\\x00-\\x20]\", name + value):\n            # Don't let us accidentally inject bad stuff\n            raise ValueError(\"Invalid cookie %r: %r\" % (name, value))\n        if not hasattr(self, \"_new_cookie\"):\n            self._new_cookie = Cookie.SimpleCookie()\n        if name in self._new_cookie:\n            del self._new_cookie[name]\n        self._new_cookie[name] = value\n        morsel = self._new_cookie[name]\n        if domain:\n            morsel[\"domain\"] = domain\n        if expires_days is not None and not expires:\n            expires = datetime.datetime.utcnow() + datetime.timedelta(\n                days=expires_days)\n        if expires:\n            morsel[\"expires\"] = httputil.format_timestamp(expires)\n        if path:\n            morsel[\"path\"] = path\n        for k, v in kwargs.items():\n            if k == 'max_age':\n                k = 'max-age'\n            morsel[k] = v\n\n    def clear_cookie(self, name, path=\"/\", domain=None):\n        \"\"\"Deletes the cookie with the given name.\"\"\"\n        expires = datetime.datetime.utcnow() - datetime.timedelta(days=365)\n        self.set_cookie(name, value=\"\", path=path, expires=expires,\n                        domain=domain)\n\n    def clear_all_cookies(self):\n        \"\"\"Deletes all the cookies the user sent with this request.\"\"\"\n        for name in self.request.cookies:\n            self.clear_cookie(name)\n\n    def set_secure_cookie(self, name, value, expires_days=30, **kwargs):\n        \"\"\"Signs and timestamps a cookie so it cannot be forged.\n\n        You must specify the ``cookie_secret`` setting in your Application\n        to use this method. It should be a long, random sequence of bytes\n        to be used as the HMAC secret for the signature.\n\n        To read a cookie set with this method, use `get_secure_cookie()`.\n\n        Note that the ``expires_days`` parameter sets the lifetime of the\n        cookie in the browser, but is independent of the ``max_age_days``\n        parameter to `get_secure_cookie`.\n\n        Secure cookies may contain arbitrary byte values, not just unicode\n        strings (unlike regular cookies)\n        \"\"\"\n        self.set_cookie(name, self.create_signed_value(name, value),\n                        expires_days=expires_days, **kwargs)\n\n    def create_signed_value(self, name, value):\n        \"\"\"Signs and timestamps a string so it cannot be forged.\n\n        Normally used via set_secure_cookie, but provided as a separate\n        method for non-cookie uses.  To decode a value not stored\n        as a cookie use the optional value argument to get_secure_cookie.\n        \"\"\"\n        self.require_setting(\"cookie_secret\", \"secure cookies\")\n        return create_signed_value(self.application.settings[\"cookie_secret\"],\n                                   name, value)\n\n    def get_secure_cookie(self, name, value=None, max_age_days=31):\n        \"\"\"Returns the given signed cookie if it validates, or None.\n\n        The decoded cookie value is returned as a byte string (unlike\n        `get_cookie`).\n        \"\"\"\n        self.require_setting(\"cookie_secret\", \"secure cookies\")\n        if value is None:\n            value = self.get_cookie(name)\n        return decode_signed_value(self.application.settings[\"cookie_secret\"],\n                                   name, value, max_age_days=max_age_days)\n\n    def redirect(self, url, permanent=False, status=None):\n        \"\"\"Sends a redirect to the given (optionally relative) URL.\n\n        If the ``status`` argument is specified, that value is used as the\n        HTTP status code; otherwise either 301 (permanent) or 302\n        (temporary) is chosen based on the ``permanent`` argument.\n        The default is 302 (temporary).\n        \"\"\"\n        if self._headers_written:\n            raise Exception(\"Cannot redirect after headers have been written\")\n        if status is None:\n            status = 301 if permanent else 302\n        else:\n            assert isinstance(status, int) and 300 <= status <= 399\n        self.set_status(status)\n        self.set_header(\"Location\", urlparse.urljoin(utf8(self.request.uri),\n                                                     utf8(url)))\n        self.finish()\n\n    def write(self, chunk):\n        \"\"\"Writes the given chunk to the output buffer.\n\n        To write the output to the network, use the flush() method below.\n\n        If the given chunk is a dictionary, we write it as JSON and set\n        the Content-Type of the response to be ``application/json``.\n        (if you want to send JSON as a different ``Content-Type``, call\n        set_header *after* calling write()).\n\n        Note that lists are not converted to JSON because of a potential\n        cross-site security vulnerability.  All JSON output should be\n        wrapped in a dictionary.  More details at\n        http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx\n        \"\"\"\n        if self._finished:\n            raise RuntimeError(\"Cannot write() after finish().  May be caused \"\n                               \"by using async operations without the \"\n                               \"@asynchronous decorator.\")\n        if isinstance(chunk, dict):\n            chunk = escape.json_encode(chunk)\n            self.set_header(\"Content-Type\", \"application/json; charset=UTF-8\")\n        chunk = utf8(chunk)\n        self._write_buffer.append(chunk)\n\n    def render(self, template_name, **kwargs):\n        \"\"\"Renders the template with the given arguments as the response.\"\"\"\n        html = self.render_string(template_name, **kwargs)\n\n        # Insert the additional JS and CSS added by the modules on the page\n        js_embed = []\n        js_files = []\n        css_embed = []\n        css_files = []\n        html_heads = []\n        html_bodies = []\n        for module in getattr(self, \"_active_modules\", {}).values():\n            embed_part = module.embedded_javascript()\n            if embed_part:\n                js_embed.append(utf8(embed_part))\n            file_part = module.javascript_files()\n            if file_part:\n                if isinstance(file_part, (unicode_type, bytes_type)):\n                    js_files.append(file_part)\n                else:\n                    js_files.extend(file_part)\n            embed_part = module.embedded_css()\n            if embed_part:\n                css_embed.append(utf8(embed_part))\n            file_part = module.css_files()\n            if file_part:\n                if isinstance(file_part, (unicode_type, bytes_type)):\n                    css_files.append(file_part)\n                else:\n                    css_files.extend(file_part)\n            head_part = module.html_head()\n            if head_part:\n                html_heads.append(utf8(head_part))\n            body_part = module.html_body()\n            if body_part:\n                html_bodies.append(utf8(body_part))\n\n        def is_absolute(path):\n            return any(path.startswith(x) for x in [\"/\", \"http:\", \"https:\"])\n        if js_files:\n            # Maintain order of JavaScript files given by modules\n            paths = []\n            unique_paths = set()\n            for path in js_files:\n                if not is_absolute(path):\n                    path = self.static_url(path)\n                if path not in unique_paths:\n                    paths.append(path)\n                    unique_paths.add(path)\n            js = ''.join('<script src=\"' + escape.xhtml_escape(p) +\n                         '\" type=\"text/javascript\"></script>'\n                         for p in paths)\n            sloc = html.rindex(b'</body>')\n            html = html[:sloc] + utf8(js) + b'\\n' + html[sloc:]\n        if js_embed:\n            js = b'<script type=\"text/javascript\">\\n//<![CDATA[\\n' + \\\n                b'\\n'.join(js_embed) + b'\\n//]]>\\n</script>'\n            sloc = html.rindex(b'</body>')\n            html = html[:sloc] + js + b'\\n' + html[sloc:]\n        if css_files:\n            paths = []\n            unique_paths = set()\n            for path in css_files:\n                if not is_absolute(path):\n                    path = self.static_url(path)\n                if path not in unique_paths:\n                    paths.append(path)\n                    unique_paths.add(path)\n            css = ''.join('<link href=\"' + escape.xhtml_escape(p) + '\" '\n                          'type=\"text/css\" rel=\"stylesheet\"/>'\n                          for p in paths)\n            hloc = html.index(b'</head>')\n            html = html[:hloc] + utf8(css) + b'\\n' + html[hloc:]\n        if css_embed:\n            css = b'<style type=\"text/css\">\\n' + b'\\n'.join(css_embed) + \\\n                b'\\n</style>'\n            hloc = html.index(b'</head>')\n            html = html[:hloc] + css + b'\\n' + html[hloc:]\n        if html_heads:\n            hloc = html.index(b'</head>')\n            html = html[:hloc] + b''.join(html_heads) + b'\\n' + html[hloc:]\n        if html_bodies:\n            hloc = html.index(b'</body>')\n            html = html[:hloc] + b''.join(html_bodies) + b'\\n' + html[hloc:]\n        self.finish(html)\n\n    def render_string(self, template_name, **kwargs):\n        \"\"\"Generate the given template with the given arguments.\n\n        We return the generated byte string (in utf8). To generate and\n        write a template as a response, use render() above.\n        \"\"\"\n        # If no template_path is specified, use the path of the calling file\n        template_path = self.get_template_path()\n        if not template_path:\n            frame = sys._getframe(0)\n            web_file = frame.f_code.co_filename\n            while frame.f_code.co_filename == web_file:\n                frame = frame.f_back\n            template_path = os.path.dirname(frame.f_code.co_filename)\n        with RequestHandler._template_loader_lock:\n            if template_path not in RequestHandler._template_loaders:\n                loader = self.create_template_loader(template_path)\n                RequestHandler._template_loaders[template_path] = loader\n            else:\n                loader = RequestHandler._template_loaders[template_path]\n        t = loader.load(template_name)\n        namespace = self.get_template_namespace()\n        namespace.update(kwargs)\n        return t.generate(**namespace)\n\n    def get_template_namespace(self):\n        \"\"\"Returns a dictionary to be used as the default template namespace.\n\n        May be overridden by subclasses to add or modify values.\n\n        The results of this method will be combined with additional\n        defaults in the `tornado.template` module and keyword arguments\n        to `render` or `render_string`.\n        \"\"\"\n        namespace = dict(\n            handler=self,\n            request=self.request,\n            current_user=self.current_user,\n            locale=self.locale,\n            _=self.locale.translate,\n            static_url=self.static_url,\n            xsrf_form_html=self.xsrf_form_html,\n            reverse_url=self.reverse_url\n        )\n        namespace.update(self.ui)\n        return namespace\n\n    def create_template_loader(self, template_path):\n        \"\"\"Returns a new template loader for the given path.\n\n        May be overridden by subclasses.  By default returns a\n        directory-based loader on the given path, using the\n        ``autoescape`` application setting.  If a ``template_loader``\n        application setting is supplied, uses that instead.\n        \"\"\"\n        settings = self.application.settings\n        if \"template_loader\" in settings:\n            return settings[\"template_loader\"]\n        kwargs = {}\n        if \"autoescape\" in settings:\n            # autoescape=None means \"no escaping\", so we have to be sure\n            # to only pass this kwarg if the user asked for it.\n            kwargs[\"autoescape\"] = settings[\"autoescape\"]\n        return template.Loader(template_path, **kwargs)\n\n    def flush(self, include_footers=False, callback=None):\n        \"\"\"Flushes the current output buffer to the network.\n\n        The ``callback`` argument, if given, can be used for flow control:\n        it will be run when all flushed data has been written to the socket.\n        Note that only one flush callback can be outstanding at a time;\n        if another flush occurs before the previous flush's callback\n        has been run, the previous callback will be discarded.\n        \"\"\"\n        if self.application._wsgi:\n            # WSGI applications cannot usefully support flush, so just make\n            # it a no-op (and run the callback immediately).\n            if callback is not None:\n                callback()\n            return\n\n        chunk = b\"\".join(self._write_buffer)\n        self._write_buffer = []\n        if not self._headers_written:\n            self._headers_written = True\n            for transform in self._transforms:\n                self._status_code, self._headers, chunk = \\\n                    transform.transform_first_chunk(\n                        self._status_code, self._headers, chunk, include_footers)\n            headers = self._generate_headers()\n        else:\n            for transform in self._transforms:\n                chunk = transform.transform_chunk(chunk, include_footers)\n            headers = b\"\"\n\n        # Ignore the chunk and only write the headers for HEAD requests\n        if self.request.method == \"HEAD\":\n            if headers:\n                self.request.write(headers, callback=callback)\n            return\n\n        self.request.write(headers + chunk, callback=callback)\n\n    def finish(self, chunk=None):\n        \"\"\"Finishes this response, ending the HTTP request.\"\"\"\n        if self._finished:\n            raise RuntimeError(\"finish() called twice.  May be caused \"\n                               \"by using async operations without the \"\n                               \"@asynchronous decorator.\")\n\n        if chunk is not None:\n            self.write(chunk)\n\n        # Automatically support ETags and add the Content-Length header if\n        # we have not flushed any content yet.\n        if not self._headers_written:\n            if (self._status_code == 200 and\n                self.request.method in (\"GET\", \"HEAD\") and\n                    \"Etag\" not in self._headers):\n                self.set_etag_header()\n                if self.check_etag_header():\n                    self._write_buffer = []\n                    self.set_status(304)\n            if self._status_code == 304:\n                assert not self._write_buffer, \"Cannot send body with 304\"\n                self._clear_headers_for_304()\n            elif \"Content-Length\" not in self._headers:\n                content_length = sum(len(part) for part in self._write_buffer)\n                self.set_header(\"Content-Length\", content_length)\n\n        if hasattr(self.request, \"connection\"):\n            # Now that the request is finished, clear the callback we\n            # set on the IOStream (which would otherwise prevent the\n            # garbage collection of the RequestHandler when there\n            # are keepalive connections)\n            self.request.connection.stream.set_close_callback(None)\n\n        if not self.application._wsgi:\n            self.flush(include_footers=True)\n            self.request.finish()\n            self._log()\n        self._finished = True\n        self.on_finish()\n        # Break up a reference cycle between this handler and the\n        # _ui_module closures to allow for faster GC on CPython.\n        self.ui = None\n\n    def send_error(self, status_code=500, **kwargs):\n        \"\"\"Sends the given HTTP error code to the browser.\n\n        If `flush()` has already been called, it is not possible to send\n        an error, so this method will simply terminate the response.\n        If output has been written but not yet flushed, it will be discarded\n        and replaced with the error page.\n\n        Override `write_error()` to customize the error page that is returned.\n        Additional keyword arguments are passed through to `write_error`.\n        \"\"\"\n        if self._headers_written:\n            gen_log.error(\"Cannot send error response after headers written\")\n            if not self._finished:\n                self.finish()\n            return\n        self.clear()\n\n        reason = None\n        if 'exc_info' in kwargs:\n            exception = kwargs['exc_info'][1]\n            if isinstance(exception, HTTPError) and exception.reason:\n                reason = exception.reason\n        self.set_status(status_code, reason=reason)\n        try:\n            self.write_error(status_code, **kwargs)\n        except Exception:\n            app_log.error(\"Uncaught exception in write_error\", exc_info=True)\n        if not self._finished:\n            self.finish()\n\n    def write_error(self, status_code, **kwargs):\n        \"\"\"Override to implement custom error pages.\n\n        ``write_error`` may call `write`, `render`, `set_header`, etc\n        to produce output as usual.\n\n        If this error was caused by an uncaught exception (including\n        HTTPError), an ``exc_info`` triple will be available as\n        ``kwargs[\"exc_info\"]``.  Note that this exception may not be\n        the \"current\" exception for purposes of methods like\n        ``sys.exc_info()`` or ``traceback.format_exc``.\n\n        For historical reasons, if a method ``get_error_html`` exists,\n        it will be used instead of the default ``write_error`` implementation.\n        ``get_error_html`` returned a string instead of producing output\n        normally, and had different semantics for exception handling.\n        Users of ``get_error_html`` are encouraged to convert their code\n        to override ``write_error`` instead.\n        \"\"\"\n        if hasattr(self, 'get_error_html'):\n            if 'exc_info' in kwargs:\n                exc_info = kwargs.pop('exc_info')\n                kwargs['exception'] = exc_info[1]\n                try:\n                    # Put the traceback into sys.exc_info()\n                    raise_exc_info(exc_info)\n                except Exception:\n                    self.finish(self.get_error_html(status_code, **kwargs))\n            else:\n                self.finish(self.get_error_html(status_code, **kwargs))\n            return\n        if self.settings.get(\"debug\") and \"exc_info\" in kwargs:\n            # in debug mode, try to send a traceback\n            self.set_header('Content-Type', 'text/plain')\n            for line in traceback.format_exception(*kwargs[\"exc_info\"]):\n                self.write(line)\n            self.finish()\n        else:\n            self.finish(\"<html><title>%(code)d: %(message)s</title>\"\n                        \"<body>%(code)d: %(message)s</body></html>\" % {\n                            \"code\": status_code,\n                            \"message\": self._reason,\n                        })\n\n    @property\n    def locale(self):\n        \"\"\"The local for the current session.\n\n        Determined by either `get_user_locale`, which you can override to\n        set the locale based on, e.g., a user preference stored in a\n        database, or `get_browser_locale`, which uses the ``Accept-Language``\n        header.\n        \"\"\"\n        if not hasattr(self, \"_locale\"):\n            self._locale = self.get_user_locale()\n            if not self._locale:\n                self._locale = self.get_browser_locale()\n                assert self._locale\n        return self._locale\n\n    def get_user_locale(self):\n        \"\"\"Override to determine the locale from the authenticated user.\n\n        If None is returned, we fall back to `get_browser_locale()`.\n\n        This method should return a `tornado.locale.Locale` object,\n        most likely obtained via a call like ``tornado.locale.get(\"en\")``\n        \"\"\"\n        return None\n\n    def get_browser_locale(self, default=\"en_US\"):\n        \"\"\"Determines the user's locale from ``Accept-Language`` header.\n\n        See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4\n        \"\"\"\n        if \"Accept-Language\" in self.request.headers:\n            languages = self.request.headers[\"Accept-Language\"].split(\",\")\n            locales = []\n            for language in languages:\n                parts = language.strip().split(\";\")\n                if len(parts) > 1 and parts[1].startswith(\"q=\"):\n                    try:\n                        score = float(parts[1][2:])\n                    except (ValueError, TypeError):\n                        score = 0.0\n                else:\n                    score = 1.0\n                locales.append((parts[0], score))\n            if locales:\n                locales.sort(key=lambda pair: pair[1], reverse=True)\n                codes = [l[0] for l in locales]\n                return locale.get(*codes)\n        return locale.get(default)\n\n    @property\n    def current_user(self):\n        \"\"\"The authenticated user for this request.\n\n        This is a cached version of `get_current_user`, which you can\n        override to set the user based on, e.g., a cookie. If that\n        method is not overridden, this method always returns None.\n\n        We lazy-load the current user the first time this method is called\n        and cache the result after that.\n        \"\"\"\n        if not hasattr(self, \"_current_user\"):\n            self._current_user = self.get_current_user()\n        return self._current_user\n\n    @current_user.setter\n    def current_user(self, value):\n        self._current_user = value\n\n    def get_current_user(self):\n        \"\"\"Override to determine the current user from, e.g., a cookie.\"\"\"\n        return None\n\n    def get_login_url(self):\n        \"\"\"Override to customize the login URL based on the request.\n\n        By default, we use the ``login_url`` application setting.\n        \"\"\"\n        self.require_setting(\"login_url\", \"@tornado.web.authenticated\")\n        return self.application.settings[\"login_url\"]\n\n    def get_template_path(self):\n        \"\"\"Override to customize template path for each handler.\n\n        By default, we use the ``template_path`` application setting.\n        Return None to load templates relative to the calling file.\n        \"\"\"\n        return self.application.settings.get(\"template_path\")\n\n    @property\n    def xsrf_token(self):\n        \"\"\"The XSRF-prevention token for the current user/session.\n\n        To prevent cross-site request forgery, we set an '_xsrf' cookie\n        and include the same '_xsrf' value as an argument with all POST\n        requests. If the two do not match, we reject the form submission\n        as a potential forgery.\n\n        See http://en.wikipedia.org/wiki/Cross-site_request_forgery\n        \"\"\"\n        if not hasattr(self, \"_xsrf_token\"):\n            token = self.get_cookie(\"_xsrf\")\n            if not token:\n                token = binascii.b2a_hex(uuid.uuid4().bytes)\n                expires_days = 30 if self.current_user else None\n                self.set_cookie(\"_xsrf\", token, expires_days=expires_days)\n            self._xsrf_token = token\n        return self._xsrf_token\n\n    def check_xsrf_cookie(self):\n        \"\"\"Verifies that the ``_xsrf`` cookie matches the ``_xsrf`` argument.\n\n        To prevent cross-site request forgery, we set an ``_xsrf``\n        cookie and include the same value as a non-cookie\n        field with all ``POST`` requests. If the two do not match, we\n        reject the form submission as a potential forgery.\n\n        The ``_xsrf`` value may be set as either a form field named ``_xsrf``\n        or in a custom HTTP header named ``X-XSRFToken`` or ``X-CSRFToken``\n        (the latter is accepted for compatibility with Django).\n\n        See http://en.wikipedia.org/wiki/Cross-site_request_forgery\n\n        Prior to release 1.1.1, this check was ignored if the HTTP header\n        ``X-Requested-With: XMLHTTPRequest`` was present.  This exception\n        has been shown to be insecure and has been removed.  For more\n        information please see\n        http://www.djangoproject.com/weblog/2011/feb/08/security/\n        http://weblog.rubyonrails.org/2011/2/8/csrf-protection-bypass-in-ruby-on-rails\n        \"\"\"\n        token = (self.get_argument(\"_xsrf\", None) or\n                 self.request.headers.get(\"X-Xsrftoken\") or\n                 self.request.headers.get(\"X-Csrftoken\"))\n        if not token:\n            raise HTTPError(403, \"'_xsrf' argument missing from POST\")\n        if self.xsrf_token != token:\n            raise HTTPError(403, \"XSRF cookie does not match POST argument\")\n\n    def xsrf_form_html(self):\n        \"\"\"An HTML ``<input/>`` element to be included with all POST forms.\n\n        It defines the ``_xsrf`` input value, which we check on all POST\n        requests to prevent cross-site request forgery. If you have set\n        the ``xsrf_cookies`` application setting, you must include this\n        HTML within all of your HTML forms.\n\n        In a template, this method should be called with ``{% module\n        xsrf_form_html() %}``\n\n        See `check_xsrf_cookie()` above for more information.\n        \"\"\"\n        return '<input type=\"hidden\" name=\"_xsrf\" value=\"' + \\\n            escape.xhtml_escape(self.xsrf_token) + '\"/>'\n\n    def static_url(self, path, include_host=None, **kwargs):\n        \"\"\"Returns a static URL for the given relative static file path.\n\n        This method requires you set the ``static_path`` setting in your\n        application (which specifies the root directory of your static\n        files).\n\n        This method returns a versioned url (by default appending\n        ``?v=<signature>``), which allows the static files to be\n        cached indefinitely.  This can be disabled by passing\n        ``include_version=False`` (in the default implementation;\n        other static file implementations are not required to support\n        this, but they may support other options).\n\n        By default this method returns URLs relative to the current\n        host, but if ``include_host`` is true the URL returned will be\n        absolute.  If this handler has an ``include_host`` attribute,\n        that value will be used as the default for all `static_url`\n        calls that do not pass ``include_host`` as a keyword argument.\n\n        \"\"\"\n        self.require_setting(\"static_path\", \"static_url\")\n        get_url = self.settings.get(\"static_handler_class\",\n                                    StaticFileHandler).make_static_url\n\n        if include_host is None:\n            include_host = getattr(self, \"include_host\", False)\n\n        if include_host:\n            base = self.request.protocol + \"://\" + self.request.host\n        else:\n            base = \"\"\n\n        return base + get_url(self.settings, path, **kwargs)\n\n    def async_callback(self, callback, *args, **kwargs):\n        \"\"\"Obsolete - catches exceptions from the wrapped function.\n\n        This function is unnecessary since Tornado 1.1.\n        \"\"\"\n        if callback is None:\n            return None\n        if args or kwargs:\n            callback = functools.partial(callback, *args, **kwargs)\n\n        def wrapper(*args, **kwargs):\n            try:\n                return callback(*args, **kwargs)\n            except Exception as e:\n                if self._headers_written:\n                    app_log.error(\"Exception after headers written\",\n                                  exc_info=True)\n                else:\n                    self._handle_request_exception(e)\n        return wrapper\n\n    def require_setting(self, name, feature=\"this feature\"):\n        \"\"\"Raises an exception if the given app setting is not defined.\"\"\"\n        if not self.application.settings.get(name):\n            raise Exception(\"You must define the '%s' setting in your \"\n                            \"application to use %s\" % (name, feature))\n\n    def reverse_url(self, name, *args):\n        \"\"\"Alias for `Application.reverse_url`.\"\"\"\n        return self.application.reverse_url(name, *args)\n\n    def compute_etag(self):\n        \"\"\"Computes the etag header to be used for this request.\n\n        By default uses a hash of the content written so far.\n\n        May be overridden to provide custom etag implementations,\n        or may return None to disable tornado's default etag support.\n        \"\"\"\n        hasher = hashlib.sha1()\n        for part in self._write_buffer:\n            hasher.update(part)\n        return '\"%s\"' % hasher.hexdigest()\n\n    def set_etag_header(self):\n        \"\"\"Sets the response's Etag header using ``self.compute_etag()``.\n\n        Note: no header will be set if ``compute_etag()`` returns ``None``.\n\n        This method is called automatically when the request is finished.\n        \"\"\"\n        etag = self.compute_etag()\n        if etag is not None:\n            self.set_header(\"Etag\", etag)\n\n    def check_etag_header(self):\n        \"\"\"Checks the ``Etag`` header against requests's ``If-None-Match``.\n\n        Returns ``True`` if the request's Etag matches and a 304 should be\n        returned. For example::\n\n            self.set_etag_header()\n            if self.check_etag_header():\n                self.set_status(304)\n                return\n\n        This method is called automatically when the request is finished,\n        but may be called earlier for applications that override\n        `compute_etag` and want to do an early check for ``If-None-Match``\n        before completing the request.  The ``Etag`` header should be set\n        (perhaps with `set_etag_header`) before calling this method.\n        \"\"\"\n        etag = self._headers.get(\"Etag\")\n        inm = utf8(self.request.headers.get(\"If-None-Match\", \"\"))\n        return bool(etag and inm and inm.find(etag) >= 0)\n\n    def _stack_context_handle_exception(self, type, value, traceback):\n        try:\n            # For historical reasons _handle_request_exception only takes\n            # the exception value instead of the full triple,\n            # so re-raise the exception to ensure that it's in\n            # sys.exc_info()\n            raise_exc_info((type, value, traceback))\n        except Exception:\n            self._handle_request_exception(value)\n        return True\n\n    def _execute(self, transforms, *args, **kwargs):\n        \"\"\"Executes this request with the given output transforms.\"\"\"\n        self._transforms = transforms\n        try:\n            if self.request.method not in self.SUPPORTED_METHODS:\n                raise HTTPError(405)\n            self.path_args = [self.decode_argument(arg) for arg in args]\n            self.path_kwargs = dict((k, self.decode_argument(v, name=k))\n                                    for (k, v) in kwargs.items())\n            # If XSRF cookies are turned on, reject form submissions without\n            # the proper cookie\n            if self.request.method not in (\"GET\", \"HEAD\", \"OPTIONS\") and \\\n                    self.application.settings.get(\"xsrf_cookies\"):\n                self.check_xsrf_cookie()\n            self._when_complete(self.prepare(), self._execute_method)\n        except Exception as e:\n            self._handle_request_exception(e)\n\n    def _when_complete(self, result, callback):\n        try:\n            if result is None:\n                callback()\n            elif isinstance(result, Future):\n                if result.done():\n                    if result.result() is not None:\n                        raise ValueError('Expected None, got %r' % result.result())\n                    callback()\n                else:\n                    # Delayed import of IOLoop because it's not available\n                    # on app engine\n                    from tornado.ioloop import IOLoop\n                    IOLoop.current().add_future(\n                        result, functools.partial(self._when_complete,\n                                                  callback=callback))\n            else:\n                raise ValueError(\"Expected Future or None, got %r\" % result)\n        except Exception as e:\n            self._handle_request_exception(e)\n\n    def _execute_method(self):\n        if not self._finished:\n            method = getattr(self, self.request.method.lower())\n            self._when_complete(method(*self.path_args, **self.path_kwargs),\n                                self._execute_finish)\n\n    def _execute_finish(self):\n        if self._auto_finish and not self._finished:\n            self.finish()\n\n    def _generate_headers(self):\n        reason = self._reason\n        lines = [utf8(self.request.version + \" \" +\n                      str(self._status_code) +\n                      \" \" + reason)]\n        lines.extend([utf8(n) + b\": \" + utf8(v) for n, v in self._headers.get_all()])\n\n        if hasattr(self, \"_new_cookie\"):\n            for cookie in self._new_cookie.values():\n                lines.append(utf8(\"Set-Cookie: \" + cookie.OutputString(None)))\n        return b\"\\r\\n\".join(lines) + b\"\\r\\n\\r\\n\"\n\n    def _log(self):\n        \"\"\"Logs the current request.\n\n        Sort of deprecated since this functionality was moved to the\n        Application, but left in place for the benefit of existing apps\n        that have overridden this method.\n        \"\"\"\n        self.application.log_request(self)\n\n    def _request_summary(self):\n        return self.request.method + \" \" + self.request.uri + \\\n            \" (\" + self.request.remote_ip + \")\"\n\n    def _handle_request_exception(self, e):\n        self.log_exception(*sys.exc_info())\n        if self._finished:\n            # Extra errors after the request has been finished should\n            # be logged, but there is no reason to continue to try and\n            # send a response.\n            return\n        if isinstance(e, HTTPError):\n            if e.status_code not in httputil.responses and not e.reason:\n                gen_log.error(\"Bad HTTP status code: %d\", e.status_code)\n                self.send_error(500, exc_info=sys.exc_info())\n            else:\n                self.send_error(e.status_code, exc_info=sys.exc_info())\n        else:\n            self.send_error(500, exc_info=sys.exc_info())\n\n    def log_exception(self, typ, value, tb):\n        \"\"\"Override to customize logging of uncaught exceptions.\n\n        By default logs instances of `HTTPError` as warnings without\n        stack traces (on the ``tornado.general`` logger), and all\n        other exceptions as errors with stack traces (on the\n        ``tornado.application`` logger).\n\n        .. versionadded:: 3.1\n        \"\"\"\n        if isinstance(value, HTTPError):\n            if value.log_message:\n                format = \"%d %s: \" + value.log_message\n                args = ([value.status_code, self._request_summary()] +\n                        list(value.args))\n                gen_log.warning(format, *args)\n        else:\n            app_log.error(\"Uncaught exception %s\\n%r\", self._request_summary(),\n                          self.request, exc_info=(typ, value, tb))\n\n    def _ui_module(self, name, module):\n        def render(*args, **kwargs):\n            if not hasattr(self, \"_active_modules\"):\n                self._active_modules = {}\n            if name not in self._active_modules:\n                self._active_modules[name] = module(self)\n            rendered = self._active_modules[name].render(*args, **kwargs)\n            return rendered\n        return render\n\n    def _ui_method(self, method):\n        return lambda *args, **kwargs: method(self, *args, **kwargs)\n\n    def _clear_headers_for_304(self):\n        # 304 responses should not contain entity headers (defined in\n        # http://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html#sec7.1)\n        # not explicitly allowed by\n        # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5\n        headers = [\"Allow\", \"Content-Encoding\", \"Content-Language\",\n                   \"Content-Length\", \"Content-MD5\", \"Content-Range\",\n                   \"Content-Type\", \"Last-Modified\"]\n        for h in headers:\n            self.clear_header(h)\n\n\ndef asynchronous(method):\n    \"\"\"Wrap request handler methods with this if they are asynchronous.\n\n    This decorator is unnecessary if the method is also decorated with\n    ``@gen.coroutine`` (it is legal but unnecessary to use the two\n    decorators together, in which case ``@asynchronous`` must be\n    first).\n\n    This decorator should only be applied to the :ref:`HTTP verb\n    methods <verbs>`; its behavior is undefined for any other method.\n    This decorator does not *make* a method asynchronous; it tells\n    the framework that the method *is* asynchronous.  For this decorator\n    to be useful the method must (at least sometimes) do something\n    asynchronous.\n\n    If this decorator is given, the response is not finished when the\n    method returns. It is up to the request handler to call\n    `self.finish() <RequestHandler.finish>` to finish the HTTP\n    request. Without this decorator, the request is automatically\n    finished when the ``get()`` or ``post()`` method returns. Example::\n\n       class MyRequestHandler(web.RequestHandler):\n           @web.asynchronous\n           def get(self):\n              http = httpclient.AsyncHTTPClient()\n              http.fetch(\"http://friendfeed.com/\", self._on_download)\n\n           def _on_download(self, response):\n              self.write(\"Downloaded!\")\n              self.finish()\n\n    .. versionadded:: 3.1\n       The ability to use ``@gen.coroutine`` without ``@asynchronous``.\n    \"\"\"\n    # Delay the IOLoop import because it's not available on app engine.\n    from tornado.ioloop import IOLoop\n    @functools.wraps(method)\n    def wrapper(self, *args, **kwargs):\n        if self.application._wsgi:\n            raise Exception(\"@asynchronous is not supported for WSGI apps\")\n        self._auto_finish = False\n        with stack_context.ExceptionStackContext(\n                self._stack_context_handle_exception):\n            result = method(self, *args, **kwargs)\n            if isinstance(result, Future):\n                # If @asynchronous is used with @gen.coroutine, (but\n                # not @gen.engine), we can automatically finish the\n                # request when the future resolves.  Additionally,\n                # the Future will swallow any exceptions so we need\n                # to throw them back out to the stack context to finish\n                # the request.\n                def future_complete(f):\n                    f.result()\n                    if not self._finished:\n                        self.finish()\n                IOLoop.current().add_future(result, future_complete)\n            return result\n    return wrapper\n\n\ndef removeslash(method):\n    \"\"\"Use this decorator to remove trailing slashes from the request path.\n\n    For example, a request to ``/foo/`` would redirect to ``/foo`` with this\n    decorator. Your request handler mapping should use a regular expression\n    like ``r'/foo/*'`` in conjunction with using the decorator.\n    \"\"\"\n    @functools.wraps(method)\n    def wrapper(self, *args, **kwargs):\n        if self.request.path.endswith(\"/\"):\n            if self.request.method in (\"GET\", \"HEAD\"):\n                uri = self.request.path.rstrip(\"/\")\n                if uri:  # don't try to redirect '/' to ''\n                    if self.request.query:\n                        uri += \"?\" + self.request.query\n                    self.redirect(uri, permanent=True)\n                    return\n            else:\n                raise HTTPError(404)\n        return method(self, *args, **kwargs)\n    return wrapper\n\n\ndef addslash(method):\n    \"\"\"Use this decorator to add a missing trailing slash to the request path.\n\n    For example, a request to ``/foo`` would redirect to ``/foo/`` with this\n    decorator. Your request handler mapping should use a regular expression\n    like ``r'/foo/?'`` in conjunction with using the decorator.\n    \"\"\"\n    @functools.wraps(method)\n    def wrapper(self, *args, **kwargs):\n        if not self.request.path.endswith(\"/\"):\n            if self.request.method in (\"GET\", \"HEAD\"):\n                uri = self.request.path + \"/\"\n                if self.request.query:\n                    uri += \"?\" + self.request.query\n                self.redirect(uri, permanent=True)\n                return\n            raise HTTPError(404)\n        return method(self, *args, **kwargs)\n    return wrapper\n\n\nclass Application(object):\n    \"\"\"A collection of request handlers that make up a web application.\n\n    Instances of this class are callable and can be passed directly to\n    HTTPServer to serve the application::\n\n        application = web.Application([\n            (r\"/\", MainPageHandler),\n        ])\n        http_server = httpserver.HTTPServer(application)\n        http_server.listen(8080)\n        ioloop.IOLoop.instance().start()\n\n    The constructor for this class takes in a list of `URLSpec` objects\n    or (regexp, request_class) tuples. When we receive requests, we\n    iterate over the list in order and instantiate an instance of the\n    first request class whose regexp matches the request path.\n\n    Each tuple can contain an optional third element, which should be\n    a dictionary if it is present. That dictionary is passed as\n    keyword arguments to the contructor of the handler. This pattern\n    is used for the `StaticFileHandler` in this example (note that a\n    `StaticFileHandler` can be installed automatically with the\n    static_path setting described below)::\n\n        application = web.Application([\n            (r\"/static/(.*)\", web.StaticFileHandler, {\"path\": \"/var/www\"}),\n        ])\n\n    We support virtual hosts with the `add_handlers` method, which takes in\n    a host regular expression as the first argument::\n\n        application.add_handlers(r\"www\\.myhost\\.com\", [\n            (r\"/article/([0-9]+)\", ArticleHandler),\n        ])\n\n    You can serve static files by sending the ``static_path`` setting\n    as a keyword argument. We will serve those files from the\n    ``/static/`` URI (this is configurable with the\n    ``static_url_prefix`` setting), and we will serve ``/favicon.ico``\n    and ``/robots.txt`` from the same directory.  A custom subclass of\n    `StaticFileHandler` can be specified with the\n    ``static_handler_class`` setting.\n    \"\"\"\n    def __init__(self, handlers=None, default_host=\"\", transforms=None,\n                 wsgi=False, **settings):\n        if transforms is None:\n            self.transforms = []\n            if settings.get(\"gzip\"):\n                self.transforms.append(GZipContentEncoding)\n            self.transforms.append(ChunkedTransferEncoding)\n        else:\n            self.transforms = transforms\n        self.handlers = []\n        self.named_handlers = {}\n        self.default_host = default_host\n        self.settings = settings\n        self.ui_modules = {'linkify': _linkify,\n                           'xsrf_form_html': _xsrf_form_html,\n                           'Template': TemplateModule,\n                           }\n        self.ui_methods = {}\n        self._wsgi = wsgi\n        self._load_ui_modules(settings.get(\"ui_modules\", {}))\n        self._load_ui_methods(settings.get(\"ui_methods\", {}))\n        if self.settings.get(\"static_path\"):\n            path = self.settings[\"static_path\"]\n            handlers = list(handlers or [])\n            static_url_prefix = settings.get(\"static_url_prefix\",\n                                             \"/static/\")\n            static_handler_class = settings.get(\"static_handler_class\",\n                                                StaticFileHandler)\n            static_handler_args = settings.get(\"static_handler_args\", {})\n            static_handler_args['path'] = path\n            for pattern in [re.escape(static_url_prefix) + r\"(.*)\",\n                            r\"/(favicon\\.ico)\", r\"/(robots\\.txt)\"]:\n                handlers.insert(0, (pattern, static_handler_class,\n                                    static_handler_args))\n        if handlers:\n            self.add_handlers(\".*$\", handlers)\n\n        # Automatically reload modified modules\n        if self.settings.get(\"debug\") and not wsgi:\n            from tornado import autoreload\n            autoreload.start()\n\n    def listen(self, port, address=\"\", **kwargs):\n        \"\"\"Starts an HTTP server for this application on the given port.\n\n        This is a convenience alias for creating an `.HTTPServer`\n        object and calling its listen method.  Keyword arguments not\n        supported by `HTTPServer.listen <.TCPServer.listen>` are passed to the\n        `.HTTPServer` constructor.  For advanced uses\n        (e.g. multi-process mode), do not use this method; create an\n        `.HTTPServer` and call its\n        `.TCPServer.bind`/`.TCPServer.start` methods directly.\n\n        Note that after calling this method you still need to call\n        ``IOLoop.instance().start()`` to start the server.\n        \"\"\"\n        # import is here rather than top level because HTTPServer\n        # is not importable on appengine\n        from tornado.httpserver import HTTPServer\n        server = HTTPServer(self, **kwargs)\n        server.listen(port, address)\n\n    def add_handlers(self, host_pattern, host_handlers):\n        \"\"\"Appends the given handlers to our handler list.\n\n        Host patterns are processed sequentially in the order they were\n        added. All matching patterns will be considered.\n        \"\"\"\n        if not host_pattern.endswith(\"$\"):\n            host_pattern += \"$\"\n        handlers = []\n        # The handlers with the wildcard host_pattern are a special\n        # case - they're added in the constructor but should have lower\n        # precedence than the more-precise handlers added later.\n        # If a wildcard handler group exists, it should always be last\n        # in the list, so insert new groups just before it.\n        if self.handlers and self.handlers[-1][0].pattern == '.*$':\n            self.handlers.insert(-1, (re.compile(host_pattern), handlers))\n        else:\n            self.handlers.append((re.compile(host_pattern), handlers))\n\n        for spec in host_handlers:\n            if isinstance(spec, (tuple, list)):\n                assert len(spec) in (2, 3)\n                pattern = spec[0]\n                handler = spec[1]\n\n                if isinstance(handler, str):\n                    # import the Module and instantiate the class\n                    # Must be a fully qualified name (module.ClassName)\n                    handler = import_object(handler)\n\n                if len(spec) == 3:\n                    kwargs = spec[2]\n                else:\n                    kwargs = {}\n                spec = URLSpec(pattern, handler, kwargs)\n            handlers.append(spec)\n            if spec.name:\n                if spec.name in self.named_handlers:\n                    app_log.warning(\n                        \"Multiple handlers named %s; replacing previous value\",\n                        spec.name)\n                self.named_handlers[spec.name] = spec\n\n    def add_transform(self, transform_class):\n        self.transforms.append(transform_class)\n\n    def _get_host_handlers(self, request):\n        host = request.host.lower().split(':')[0]\n        matches = []\n        for pattern, handlers in self.handlers:\n            if pattern.match(host):\n                matches.extend(handlers)\n        # Look for default host if not behind load balancer (for debugging)\n        if not matches and \"X-Real-Ip\" not in request.headers:\n            for pattern, handlers in self.handlers:\n                if pattern.match(self.default_host):\n                    matches.extend(handlers)\n        return matches or None\n\n    def _load_ui_methods(self, methods):\n        if isinstance(methods, types.ModuleType):\n            self._load_ui_methods(dict((n, getattr(methods, n))\n                                       for n in dir(methods)))\n        elif isinstance(methods, list):\n            for m in methods:\n                self._load_ui_methods(m)\n        else:\n            for name, fn in methods.items():\n                if not name.startswith(\"_\") and hasattr(fn, \"__call__\") \\\n                        and name[0].lower() == name[0]:\n                    self.ui_methods[name] = fn\n\n    def _load_ui_modules(self, modules):\n        if isinstance(modules, types.ModuleType):\n            self._load_ui_modules(dict((n, getattr(modules, n))\n                                       for n in dir(modules)))\n        elif isinstance(modules, list):\n            for m in modules:\n                self._load_ui_modules(m)\n        else:\n            assert isinstance(modules, dict)\n            for name, cls in modules.items():\n                try:\n                    if issubclass(cls, UIModule):\n                        self.ui_modules[name] = cls\n                except TypeError:\n                    pass\n\n    def __call__(self, request):\n        \"\"\"Called by HTTPServer to execute the request.\"\"\"\n        transforms = [t(request) for t in self.transforms]\n        handler = None\n        args = []\n        kwargs = {}\n        handlers = self._get_host_handlers(request)\n        if not handlers:\n            handler = RedirectHandler(\n                self, request, url=\"http://\" + self.default_host + \"/\")\n        else:\n            for spec in handlers:\n                match = spec.regex.match(request.path)\n                if match:\n                    handler = spec.handler_class(self, request, **spec.kwargs)\n                    if spec.regex.groups:\n                        # None-safe wrapper around url_unescape to handle\n                        # unmatched optional groups correctly\n                        def unquote(s):\n                            if s is None:\n                                return s\n                            return escape.url_unescape(s, encoding=None,\n                                                       plus=False)\n                        # Pass matched groups to the handler.  Since\n                        # match.groups() includes both named and unnamed groups,\n                        # we want to use either groups or groupdict but not both.\n                        # Note that args are passed as bytes so the handler can\n                        # decide what encoding to use.\n\n                        if spec.regex.groupindex:\n                            kwargs = dict(\n                                (str(k), unquote(v))\n                                for (k, v) in match.groupdict().items())\n                        else:\n                            args = [unquote(s) for s in match.groups()]\n                    break\n            if not handler:\n                handler = ErrorHandler(self, request, status_code=404)\n\n        # In debug mode, re-compile templates and reload static files on every\n        # request so you don't need to restart to see changes\n        if self.settings.get(\"debug\"):\n            with RequestHandler._template_loader_lock:\n                for loader in RequestHandler._template_loaders.values():\n                    loader.reset()\n            StaticFileHandler.reset()\n\n        handler._execute(transforms, *args, **kwargs)\n        return handler\n\n    def reverse_url(self, name, *args):\n        \"\"\"Returns a URL path for handler named ``name``\n\n        The handler must be added to the application as a named `URLSpec`.\n\n        Args will be substituted for capturing groups in the `URLSpec` regex.\n        They will be converted to strings if necessary, encoded as utf8,\n        and url-escaped.\n        \"\"\"\n        if name in self.named_handlers:\n            return self.named_handlers[name].reverse(*args)\n        raise KeyError(\"%s not found in named urls\" % name)\n\n    def log_request(self, handler):\n        \"\"\"Writes a completed HTTP request to the logs.\n\n        By default writes to the python root logger.  To change\n        this behavior either subclass Application and override this method,\n        or pass a function in the application settings dictionary as\n        ``log_function``.\n        \"\"\"\n        if \"log_function\" in self.settings:\n            self.settings[\"log_function\"](handler)\n            return\n        if handler.get_status() < 400:\n            log_method = access_log.info\n        elif handler.get_status() < 500:\n            log_method = access_log.warning\n        else:\n            log_method = access_log.error\n        request_time = 1000.0 * handler.request.request_time()\n        log_method(\"%d %s %.2fms\", handler.get_status(),\n                   handler._request_summary(), request_time)\n\n\nclass HTTPError(Exception):\n    \"\"\"An exception that will turn into an HTTP error response.\n\n    Raising an `HTTPError` is a convenient alternative to calling\n    `RequestHandler.send_error` since it automatically ends the\n    current function.\n\n    :arg int status_code: HTTP status code.  Must be listed in\n        `httplib.responses <http.client.responses>` unless the ``reason``\n        keyword argument is given.\n    :arg string log_message: Message to be written to the log for this error\n        (will not be shown to the user unless the `Application` is in debug\n        mode).  May contain ``%s``-style placeholders, which will be filled\n        in with remaining positional parameters.\n    :arg string reason: Keyword-only argument.  The HTTP \"reason\" phrase\n        to pass in the status line along with ``status_code``.  Normally\n        determined automatically from ``status_code``, but can be used\n        to use a non-standard numeric code.\n    \"\"\"\n    def __init__(self, status_code, log_message=None, *args, **kwargs):\n        self.status_code = status_code\n        self.log_message = log_message\n        self.args = args\n        self.reason = kwargs.get('reason', None)\n\n    def __str__(self):\n        message = \"HTTP %d: %s\" % (\n            self.status_code,\n            self.reason or httputil.responses.get(self.status_code, 'Unknown'))\n        if self.log_message:\n            return message + \" (\" + (self.log_message % self.args) + \")\"\n        else:\n            return message\n\n\nclass MissingArgumentError(HTTPError):\n    \"\"\"Exception raised by `RequestHandler.get_argument`.\n\n    This is a subclass of `HTTPError`, so if it is uncaught a 400 response\n    code will be used instead of 500 (and a stack trace will not be logged).\n\n    .. versionadded:: 3.1\n    \"\"\"\n    def __init__(self, arg_name):\n        super(MissingArgumentError, self).__init__(\n            400, 'Missing argument %s' % arg_name)\n        self.arg_name = arg_name\n\n\nclass ErrorHandler(RequestHandler):\n    \"\"\"Generates an error response with ``status_code`` for all requests.\"\"\"\n    def initialize(self, status_code):\n        self.set_status(status_code)\n\n    def prepare(self):\n        raise HTTPError(self._status_code)\n\n    def check_xsrf_cookie(self):\n        # POSTs to an ErrorHandler don't actually have side effects,\n        # so we don't need to check the xsrf token.  This allows POSTs\n        # to the wrong url to return a 404 instead of 403.\n        pass\n\n\nclass RedirectHandler(RequestHandler):\n    \"\"\"Redirects the client to the given URL for all GET requests.\n\n    You should provide the keyword argument ``url`` to the handler, e.g.::\n\n        application = web.Application([\n            (r\"/oldpath\", web.RedirectHandler, {\"url\": \"/newpath\"}),\n        ])\n    \"\"\"\n    def initialize(self, url, permanent=True):\n        self._url = url\n        self._permanent = permanent\n\n    def get(self):\n        self.redirect(self._url, permanent=self._permanent)\n\n\nclass StaticFileHandler(RequestHandler):\n    \"\"\"A simple handler that can serve static content from a directory.\n\n    A `StaticFileHandler` is configured automatically if you pass the\n    ``static_path`` keyword argument to `Application`.  This handler\n    can be customized with the ``static_url_prefix``, ``static_handler_class``,\n    and ``static_handler_args`` settings.\n\n    To map an additional path to this handler for a static data directory\n    you would add a line to your application like::\n\n        application = web.Application([\n            (r\"/content/(.*)\", web.StaticFileHandler, {\"path\": \"/var/www\"}),\n        ])\n\n    The handler constructor requires a ``path`` argument, which specifies the\n    local root directory of the content to be served.\n\n    Note that a capture group in the regex is required to parse the value for\n    the ``path`` argument to the get() method (different than the constructor\n    argument above); see `URLSpec` for details.\n\n    To maximize the effectiveness of browser caching, this class supports\n    versioned urls (by default using the argument ``?v=``).  If a version\n    is given, we instruct the browser to cache this file indefinitely.\n    `make_static_url` (also available as `RequestHandler.static_url`) can\n    be used to construct a versioned url.\n\n    This handler is intended primarily for use in development and light-duty\n    file serving; for heavy traffic it will be more efficient to use\n    a dedicated static file server (such as nginx or Apache).  We support\n    the HTTP ``Accept-Ranges`` mechanism to return partial content (because\n    some browsers require this functionality to be present to seek in\n    HTML5 audio or video), but this handler should not be used with\n    files that are too large to fit comfortably in memory.\n\n    **Subclassing notes**\n\n    This class is designed to be extensible by subclassing, but because\n    of the way static urls are generated with class methods rather than\n    instance methods, the inheritance patterns are somewhat unusual.\n    Be sure to use the ``@classmethod`` decorator when overriding a\n    class method.  Instance methods may use the attributes ``self.path``\n    ``self.absolute_path``, and ``self.modified``.\n\n    To change the way static urls are generated (e.g. to match the behavior\n    of another server or CDN), override `make_static_url`, `parse_url_path`,\n    `get_cache_time`, and/or `get_version`.\n\n    To replace all interaction with the filesystem (e.g. to serve\n    static content from a database), override `get_content`,\n    `get_content_size`, `get_modified_time`, `get_absolute_path`, and\n    `validate_absolute_path`.\n\n    .. versionchanged:: 3.1\n       Many of the methods for subclasses were added in Tornado 3.1.\n    \"\"\"\n    CACHE_MAX_AGE = 86400 * 365 * 10  # 10 years\n\n    _static_hashes = {}\n    _lock = threading.Lock()  # protects _static_hashes\n\n    def initialize(self, path, default_filename=None):\n        self.root = path\n        self.default_filename = default_filename\n\n    @classmethod\n    def reset(cls):\n        with cls._lock:\n            cls._static_hashes = {}\n\n    def head(self, path):\n        self.get(path, include_body=False)\n\n    def get(self, path, include_body=True):\n        # Set up our path instance variables.\n        self.path = self.parse_url_path(path)\n        del path  # make sure we don't refer to path instead of self.path again\n        absolute_path = self.get_absolute_path(self.root, self.path)\n        self.absolute_path = self.validate_absolute_path(\n            self.root, absolute_path)\n        if self.absolute_path is None:\n            return\n\n        self.modified = self.get_modified_time()\n        self.set_headers()\n\n        if self.should_return_304():\n            self.set_status(304)\n            return\n\n        request_range = None\n        range_header = self.request.headers.get(\"Range\")\n        if range_header:\n            # As per RFC 2616 14.16, if an invalid Range header is specified,\n            # the request will be treated as if the header didn't exist.\n            request_range = httputil._parse_request_range(range_header)\n\n        if request_range:\n            start, end = request_range\n            size = self.get_content_size()\n            if (start is not None and start >= size) or end == 0:\n                # As per RFC 2616 14.35.1, a range is not satisfiable only: if\n                # the first requested byte is equal to or greater than the\n                # content, or when a suffix with length 0 is specified\n                self.set_status(416)  # Range Not Satisfiable\n                self.set_header(\"Content-Type\", \"text/plain\")\n                self.set_header(\"Content-Range\", \"bytes */%s\" %(size, ))\n                return\n            if start is not None and start < 0:\n                start += size\n            if end is not None and end > size:\n                # Clients sometimes blindly use a large range to limit their\n                # download size; cap the endpoint at the actual file size.\n                end = size\n            # Note: only return HTTP 206 if less than the entire range has been\n            # requested. Not only is this semantically correct, but Chrome\n            # refuses to play audio if it gets an HTTP 206 in response to\n            # ``Range: bytes=0-``.\n            if size != (end or size) - (start or 0):\n                self.set_status(206)  # Partial Content\n                self.set_header(\"Content-Range\",\n                                httputil._get_content_range(start, end, size))\n        else:\n            start = end = None\n        content = self.get_content(self.absolute_path, start, end)\n        if isinstance(content, bytes_type):\n            content = [content]\n        content_length = 0\n        for chunk in content:\n            if include_body:\n                self.write(chunk)\n            else:\n                content_length += len(chunk)\n        if not include_body:\n            assert self.request.method == \"HEAD\"\n            self.set_header(\"Content-Length\", content_length)\n\n    def compute_etag(self):\n        \"\"\"Sets the ``Etag`` header based on static url version.\n\n        This allows efficient ``If-None-Match`` checks against cached\n        versions, and sends the correct ``Etag`` for a partial response\n        (i.e. the same ``Etag`` as the full file).\n\n        .. versionadded:: 3.1\n        \"\"\"\n        version_hash = self._get_cached_version(self.absolute_path)\n        if not version_hash:\n            return None\n        return '\"%s\"' % (version_hash, )\n\n    def set_headers(self):\n        \"\"\"Sets the content and caching headers on the response.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        self.set_header(\"Accept-Ranges\", \"bytes\")\n        self.set_etag_header()\n\n        if self.modified is not None:\n            self.set_header(\"Last-Modified\", self.modified)\n\n        content_type = self.get_content_type()\n        if content_type:\n            self.set_header(\"Content-Type\", content_type)\n\n        cache_time = self.get_cache_time(self.path, self.modified, content_type)\n        if cache_time > 0:\n            self.set_header(\"Expires\", datetime.datetime.utcnow() +\n                            datetime.timedelta(seconds=cache_time))\n            self.set_header(\"Cache-Control\", \"max-age=\" + str(cache_time))\n\n        self.set_extra_headers(self.path)\n\n    def should_return_304(self):\n        \"\"\"Returns True if the headers indicate that we should return 304.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        if self.check_etag_header():\n            return True\n\n        # Check the If-Modified-Since, and don't send the result if the\n        # content has not been modified\n        ims_value = self.request.headers.get(\"If-Modified-Since\")\n        if ims_value is not None:\n            date_tuple = email.utils.parsedate(ims_value)\n            if date_tuple is not None:\n                if_since = datetime.datetime(*date_tuple[:6])\n                if if_since >= self.modified:\n                    return True\n\n        return False\n\n    @classmethod\n    def get_absolute_path(cls, root, path):\n        \"\"\"Returns the absolute location of ``path`` relative to ``root``.\n\n        ``root`` is the path configured for this `StaticFileHandler`\n        (in most cases the ``static_path`` `Application` setting).\n\n        This class method may be overridden in subclasses.  By default\n        it returns a filesystem path, but other strings may be used\n        as long as they are unique and understood by the subclass's\n        overridden `get_content`.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        abspath = os.path.abspath(os.path.join(root, path))\n        return abspath\n\n    def validate_absolute_path(self, root, absolute_path):\n        \"\"\"Validate and return the absolute path.\n\n        ``root`` is the configured path for the `StaticFileHandler`,\n        and ``path`` is the result of `get_absolute_path`\n\n        This is an instance method called during request processing,\n        so it may raise `HTTPError` or use methods like\n        `RequestHandler.redirect` (return None after redirecting to\n        halt further processing).  This is where 404 errors for missing files\n        are generated.\n\n        This method may modify the path before returning it, but note that\n        any such modifications will not be understood by `make_static_url`.\n\n        In instance methods, this method's result is available as\n        ``self.absolute_path``.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        root = os.path.abspath(root)\n        # os.path.abspath strips a trailing /\n        # it needs to be temporarily added back for requests to root/\n        if not (absolute_path + os.path.sep).startswith(root):\n            raise HTTPError(403, \"%s is not in root static directory\",\n                            self.path)\n        if (os.path.isdir(absolute_path) and\n                self.default_filename is not None):\n            # need to look at the request.path here for when path is empty\n            # but there is some prefix to the path that was already\n            # trimmed by the routing\n            if not self.request.path.endswith(\"/\"):\n                self.redirect(self.request.path + \"/\", permanent=True)\n                return\n            absolute_path = os.path.join(absolute_path, self.default_filename)\n        if not os.path.exists(absolute_path):\n            raise HTTPError(404)\n        if not os.path.isfile(absolute_path):\n            raise HTTPError(403, \"%s is not a file\", self.path)\n        return absolute_path\n\n    @classmethod\n    def get_content(cls, abspath, start=None, end=None):\n        \"\"\"Retrieve the content of the requested resource which is located\n        at the given absolute path.\n\n        This class method may be overridden by subclasses.  Note that its\n        signature is different from other overridable class methods\n        (no ``settings`` argument); this is deliberate to ensure that\n        ``abspath`` is able to stand on its own as a cache key.\n\n        This method should either return a byte string or an iterator\n        of byte strings.  The latter is preferred for large files\n        as it helps reduce memory fragmentation.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        with open(abspath, \"rb\") as file:\n            if start is not None:\n                file.seek(start)\n            if end is not None:\n                remaining = end - (start or 0)\n            else:\n                remaining = None\n            while True:\n                chunk_size = 64 * 1024\n                if remaining is not None and remaining < chunk_size:\n                    chunk_size = remaining\n                chunk = file.read(chunk_size)\n                if chunk:\n                    if remaining is not None:\n                        remaining -= len(chunk)\n                    yield chunk\n                else:\n                    if remaining is not None:\n                        assert remaining == 0\n                    return\n\n    @classmethod\n    def get_content_version(cls, abspath):\n        \"\"\"Returns a version string for the resource at the given path.\n\n        This class method may be overridden by subclasses.  The\n        default implementation is a hash of the file's contents.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        data = cls.get_content(abspath)\n        hasher = hashlib.md5()\n        if isinstance(data, bytes_type):\n            hasher.update(data)\n        else:\n            for chunk in data:\n                hasher.update(chunk)\n        return hasher.hexdigest()\n\n    def _stat(self):\n        if not hasattr(self, '_stat_result'):\n            self._stat_result = os.stat(self.absolute_path)\n        return self._stat_result\n\n    def get_content_size(self):\n        \"\"\"Retrieve the total size of the resource at the given path.\n\n        This method may be overridden by subclasses. It will only\n        be called if a partial result is requested from `get_content`\n\n        .. versionadded:: 3.1\n        \"\"\"\n        stat_result = self._stat()\n        return stat_result[stat.ST_SIZE]\n\n    def get_modified_time(self):\n        \"\"\"Returns the time that ``self.absolute_path`` was last modified.\n\n        May be overridden in subclasses.  Should return a `~datetime.datetime`\n        object or None.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        stat_result = self._stat()\n        modified = datetime.datetime.utcfromtimestamp(stat_result[stat.ST_MTIME])\n        return modified\n\n    def get_content_type(self):\n        \"\"\"Returns the ``Content-Type`` header to be used for this request.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        mime_type, encoding = mimetypes.guess_type(self.absolute_path)\n        return mime_type\n\n    def set_extra_headers(self, path):\n        \"\"\"For subclass to add extra headers to the response\"\"\"\n        pass\n\n    def get_cache_time(self, path, modified, mime_type):\n        \"\"\"Override to customize cache control behavior.\n\n        Return a positive number of seconds to make the result\n        cacheable for that amount of time or 0 to mark resource as\n        cacheable for an unspecified amount of time (subject to\n        browser heuristics).\n\n        By default returns cache expiry of 10 years for resources requested\n        with ``v`` argument.\n        \"\"\"\n        return self.CACHE_MAX_AGE if \"v\" in self.request.arguments else 0\n\n    @classmethod\n    def make_static_url(cls, settings, path, include_version=True):\n        \"\"\"Constructs a versioned url for the given path.\n\n        This method may be overridden in subclasses (but note that it\n        is a class method rather than an instance method).  Subclasses\n        are only required to implement the signature\n        ``make_static_url(cls, settings, path)``; other keyword\n        arguments may be passed through `~RequestHandler.static_url`\n        but are not standard.\n\n        ``settings`` is the `Application.settings` dictionary.  ``path``\n        is the static path being requested.  The url returned should be\n        relative to the current host.\n\n        ``include_version`` determines whether the generated URL should\n        include the query string containing the version hash of the\n        file corresponding to the given ``path``.\n\n        \"\"\"\n        url = settings.get('static_url_prefix', '/static/') + path\n        if not include_version:\n            return url\n\n        version_hash = cls.get_version(settings, path)\n        if not version_hash:\n            return url\n\n        return '%s?v=%s' % (url, version_hash)\n\n    def parse_url_path(self, url_path):\n        \"\"\"Converts a static URL path into a filesystem path.\n\n        ``url_path`` is the path component of the URL with\n        ``static_url_prefix`` removed.  The return value should be\n        filesystem path relative to ``static_path``.\n\n        This is the inverse of `make_static_url`.\n        \"\"\"\n        if os.path.sep != \"/\":\n            url_path = url_path.replace(\"/\", os.path.sep)\n        return url_path\n\n    @classmethod\n    def get_version(cls, settings, path):\n        \"\"\"Generate the version string to be used in static URLs.\n\n        ``settings`` is the `Application.settings` dictionary and ``path``\n        is the relative location of the requested asset on the filesystem.\n        The returned value should be a string, or ``None`` if no version\n        could be determined.\n\n        .. versionchanged:: 3.1\n           This method was previously recommended for subclasses to override;\n           `get_content_version` is now preferred as it allows the base\n           class to handle caching of the result.\n        \"\"\"\n        abs_path = cls.get_absolute_path(settings['static_path'], path)\n        return cls._get_cached_version(abs_path)\n\n    @classmethod\n    def _get_cached_version(cls, abs_path):\n        with cls._lock:\n            hashes = cls._static_hashes\n            if abs_path not in hashes:\n                try:\n                    hashes[abs_path] = cls.get_content_version(abs_path)\n                except Exception:\n                    gen_log.error(\"Could not open static file %r\", abs_path)\n                    hashes[abs_path] = None\n            hsh = hashes.get(abs_path)\n            if hsh:\n                return hsh\n        return None\n\n\nclass FallbackHandler(RequestHandler):\n    \"\"\"A `RequestHandler` that wraps another HTTP server callback.\n\n    The fallback is a callable object that accepts an\n    `~.httpserver.HTTPRequest`, such as an `Application` or\n    `tornado.wsgi.WSGIContainer`.  This is most useful to use both\n    Tornado ``RequestHandlers`` and WSGI in the same server.  Typical\n    usage::\n\n        wsgi_app = tornado.wsgi.WSGIContainer(\n            django.core.handlers.wsgi.WSGIHandler())\n        application = tornado.web.Application([\n            (r\"/foo\", FooHandler),\n            (r\".*\", FallbackHandler, dict(fallback=wsgi_app),\n        ])\n    \"\"\"\n    def initialize(self, fallback):\n        self.fallback = fallback\n\n    def prepare(self):\n        self.fallback(self.request)\n        self._finished = True\n\n\nclass OutputTransform(object):\n    \"\"\"A transform modifies the result of an HTTP request (e.g., GZip encoding)\n\n    A new transform instance is created for every request. See the\n    ChunkedTransferEncoding example below if you want to implement a\n    new Transform.\n    \"\"\"\n    def __init__(self, request):\n        pass\n\n    def transform_first_chunk(self, status_code, headers, chunk, finishing):\n        return status_code, headers, chunk\n\n    def transform_chunk(self, chunk, finishing):\n        return chunk\n\n\nclass GZipContentEncoding(OutputTransform):\n    \"\"\"Applies the gzip content encoding to the response.\n\n    See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11\n    \"\"\"\n    CONTENT_TYPES = set([\n        \"text/plain\", \"text/html\", \"text/css\", \"text/xml\", \"application/javascript\",\n        \"application/x-javascript\", \"application/xml\", \"application/atom+xml\",\n        \"text/javascript\", \"application/json\", \"application/xhtml+xml\"])\n    MIN_LENGTH = 5\n\n    def __init__(self, request):\n        self._gzipping = request.supports_http_1_1() and \\\n            \"gzip\" in request.headers.get(\"Accept-Encoding\", \"\")\n\n    def transform_first_chunk(self, status_code, headers, chunk, finishing):\n        if 'Vary' in headers:\n            headers['Vary'] += b', Accept-Encoding'\n        else:\n            headers['Vary'] = b'Accept-Encoding'\n        if self._gzipping:\n            ctype = _unicode(headers.get(\"Content-Type\", \"\")).split(\";\")[0]\n            self._gzipping = (ctype in self.CONTENT_TYPES) and \\\n                (not finishing or len(chunk) >= self.MIN_LENGTH) and \\\n                (finishing or \"Content-Length\" not in headers) and \\\n                (\"Content-Encoding\" not in headers)\n        if self._gzipping:\n            headers[\"Content-Encoding\"] = \"gzip\"\n            self._gzip_value = BytesIO()\n            self._gzip_file = gzip.GzipFile(mode=\"w\", fileobj=self._gzip_value)\n            chunk = self.transform_chunk(chunk, finishing)\n            if \"Content-Length\" in headers:\n                headers[\"Content-Length\"] = str(len(chunk))\n        return status_code, headers, chunk\n\n    def transform_chunk(self, chunk, finishing):\n        if self._gzipping:\n            self._gzip_file.write(chunk)\n            if finishing:\n                self._gzip_file.close()\n            else:\n                self._gzip_file.flush()\n            chunk = self._gzip_value.getvalue()\n            self._gzip_value.truncate(0)\n            self._gzip_value.seek(0)\n        return chunk\n\n\nclass ChunkedTransferEncoding(OutputTransform):\n    \"\"\"Applies the chunked transfer encoding to the response.\n\n    See http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.6.1\n    \"\"\"\n    def __init__(self, request):\n        self._chunking = request.supports_http_1_1()\n\n    def transform_first_chunk(self, status_code, headers, chunk, finishing):\n        # 304 responses have no body (not even a zero-length body), and so\n        # should not have either Content-Length or Transfer-Encoding headers.\n        if self._chunking and status_code != 304:\n            # No need to chunk the output if a Content-Length is specified\n            if \"Content-Length\" in headers or \"Transfer-Encoding\" in headers:\n                self._chunking = False\n            else:\n                headers[\"Transfer-Encoding\"] = \"chunked\"\n                chunk = self.transform_chunk(chunk, finishing)\n        return status_code, headers, chunk\n\n    def transform_chunk(self, block, finishing):\n        if self._chunking:\n            # Don't write out empty chunks because that means END-OF-STREAM\n            # with chunked encoding\n            if block:\n                block = utf8(\"%x\" % len(block)) + b\"\\r\\n\" + block + b\"\\r\\n\"\n            if finishing:\n                block += b\"0\\r\\n\\r\\n\"\n        return block\n\n\ndef authenticated(method):\n    \"\"\"Decorate methods with this to require that the user be logged in.\n\n    If the user is not logged in, they will be redirected to the configured\n    `login url <RequestHandler.get_login_url>`.\n    \"\"\"\n    @functools.wraps(method)\n    def wrapper(self, *args, **kwargs):\n        if not self.current_user:\n            if self.request.method in (\"GET\", \"HEAD\"):\n                url = self.get_login_url()\n                if \"?\" not in url:\n                    if urlparse.urlsplit(url).scheme:\n                        # if login url is absolute, make next absolute too\n                        next_url = self.request.full_url()\n                    else:\n                        next_url = self.request.uri\n                    url += \"?\" + urlencode(dict(next=next_url))\n                self.redirect(url)\n                return\n            raise HTTPError(403)\n        return method(self, *args, **kwargs)\n    return wrapper\n\n\nclass UIModule(object):\n    \"\"\"A re-usable, modular UI unit on a page.\n\n    UI modules often execute additional queries, and they can include\n    additional CSS and JavaScript that will be included in the output\n    page, which is automatically inserted on page render.\n    \"\"\"\n    def __init__(self, handler):\n        self.handler = handler\n        self.request = handler.request\n        self.ui = handler.ui\n        self.current_user = handler.current_user\n        self.locale = handler.locale\n\n    def render(self, *args, **kwargs):\n        \"\"\"Overridden in subclasses to return this module's output.\"\"\"\n        raise NotImplementedError()\n\n    def embedded_javascript(self):\n        \"\"\"Returns a JavaScript string that will be embedded in the page.\"\"\"\n        return None\n\n    def javascript_files(self):\n        \"\"\"Returns a list of JavaScript files required by this module.\"\"\"\n        return None\n\n    def embedded_css(self):\n        \"\"\"Returns a CSS string that will be embedded in the page.\"\"\"\n        return None\n\n    def css_files(self):\n        \"\"\"Returns a list of CSS files required by this module.\"\"\"\n        return None\n\n    def html_head(self):\n        \"\"\"Returns a CSS string that will be put in the <head/> element\"\"\"\n        return None\n\n    def html_body(self):\n        \"\"\"Returns an HTML string that will be put in the <body/> element\"\"\"\n        return None\n\n    def render_string(self, path, **kwargs):\n        \"\"\"Renders a template and returns it as a string.\"\"\"\n        return self.handler.render_string(path, **kwargs)\n\n\nclass _linkify(UIModule):\n    def render(self, text, **kwargs):\n        return escape.linkify(text, **kwargs)\n\n\nclass _xsrf_form_html(UIModule):\n    def render(self):\n        return self.handler.xsrf_form_html()\n\n\nclass TemplateModule(UIModule):\n    \"\"\"UIModule that simply renders the given template.\n\n    {% module Template(\"foo.html\") %} is similar to {% include \"foo.html\" %},\n    but the module version gets its own namespace (with kwargs passed to\n    Template()) instead of inheriting the outer template's namespace.\n\n    Templates rendered through this module also get access to UIModule's\n    automatic javascript/css features.  Simply call set_resources\n    inside the template and give it keyword arguments corresponding to\n    the methods on UIModule: {{ set_resources(js_files=static_url(\"my.js\")) }}\n    Note that these resources are output once per template file, not once\n    per instantiation of the template, so they must not depend on\n    any arguments to the template.\n    \"\"\"\n    def __init__(self, handler):\n        super(TemplateModule, self).__init__(handler)\n        # keep resources in both a list and a dict to preserve order\n        self._resource_list = []\n        self._resource_dict = {}\n\n    def render(self, path, **kwargs):\n        def set_resources(**kwargs):\n            if path not in self._resource_dict:\n                self._resource_list.append(kwargs)\n                self._resource_dict[path] = kwargs\n            else:\n                if self._resource_dict[path] != kwargs:\n                    raise ValueError(\"set_resources called with different \"\n                                     \"resources for the same template\")\n            return \"\"\n        return self.render_string(path, set_resources=set_resources,\n                                  **kwargs)\n\n    def _get_resources(self, key):\n        return (r[key] for r in self._resource_list if key in r)\n\n    def embedded_javascript(self):\n        return \"\\n\".join(self._get_resources(\"embedded_javascript\"))\n\n    def javascript_files(self):\n        result = []\n        for f in self._get_resources(\"javascript_files\"):\n            if isinstance(f, (unicode_type, bytes_type)):\n                result.append(f)\n            else:\n                result.extend(f)\n        return result\n\n    def embedded_css(self):\n        return \"\\n\".join(self._get_resources(\"embedded_css\"))\n\n    def css_files(self):\n        result = []\n        for f in self._get_resources(\"css_files\"):\n            if isinstance(f, (unicode_type, bytes_type)):\n                result.append(f)\n            else:\n                result.extend(f)\n        return result\n\n    def html_head(self):\n        return \"\".join(self._get_resources(\"html_head\"))\n\n    def html_body(self):\n        return \"\".join(self._get_resources(\"html_body\"))\n\n\nclass _UIModuleNamespace(object):\n    \"\"\"Lazy namespace which creates UIModule proxies bound to a handler.\"\"\"\n    def __init__(self, handler, ui_modules):\n        self.handler = handler\n        self.ui_modules = ui_modules\n\n    def __getitem__(self, key):\n        return self.handler._ui_module(key, self.ui_modules[key])\n\n    def __getattr__(self, key):\n        try:\n            return self[key]\n        except KeyError as e:\n            raise AttributeError(str(e))\n\n\nclass URLSpec(object):\n    \"\"\"Specifies mappings between URLs and handlers.\"\"\"\n    def __init__(self, pattern, handler_class, kwargs=None, name=None):\n        \"\"\"Parameters:\n\n        * ``pattern``: Regular expression to be matched.  Any groups\n          in the regex will be passed in to the handler's get/post/etc\n          methods as arguments.\n\n        * ``handler_class``: `RequestHandler` subclass to be invoked.\n\n        * ``kwargs`` (optional): A dictionary of additional arguments\n          to be passed to the handler's constructor.\n\n        * ``name`` (optional): A name for this handler.  Used by\n          `Application.reverse_url`.\n        \"\"\"\n        if not pattern.endswith('$'):\n            pattern += '$'\n        self.regex = re.compile(pattern)\n        assert len(self.regex.groupindex) in (0, self.regex.groups), \\\n            (\"groups in url regexes must either be all named or all \"\n             \"positional: %r\" % self.regex.pattern)\n        self.handler_class = handler_class\n        self.kwargs = kwargs or {}\n        self.name = name\n        self._path, self._group_count = self._find_groups()\n\n    def __repr__(self):\n        return '%s(%r, %s, kwargs=%r, name=%r)' % \\\n            (self.__class__.__name__, self.regex.pattern,\n             self.handler_class, self.kwargs, self.name)\n\n    def _find_groups(self):\n        \"\"\"Returns a tuple (reverse string, group count) for a url.\n\n        For example: Given the url pattern /([0-9]{4})/([a-z-]+)/, this method\n        would return ('/%s/%s/', 2).\n        \"\"\"\n        pattern = self.regex.pattern\n        if pattern.startswith('^'):\n            pattern = pattern[1:]\n        if pattern.endswith('$'):\n            pattern = pattern[:-1]\n\n        if self.regex.groups != pattern.count('('):\n            # The pattern is too complicated for our simplistic matching,\n            # so we can't support reversing it.\n            return (None, None)\n\n        pieces = []\n        for fragment in pattern.split('('):\n            if ')' in fragment:\n                paren_loc = fragment.index(')')\n                if paren_loc >= 0:\n                    pieces.append('%s' + fragment[paren_loc + 1:])\n            else:\n                pieces.append(fragment)\n\n        return (''.join(pieces), self.regex.groups)\n\n    def reverse(self, *args):\n        assert self._path is not None, \\\n            \"Cannot reverse url regex \" + self.regex.pattern\n        assert len(args) == self._group_count, \"required number of arguments \"\\\n            \"not found\"\n        if not len(args):\n            return self._path\n        converted_args = []\n        for a in args:\n            if not isinstance(a, (unicode_type, bytes_type)):\n                a = str(a)\n            converted_args.append(escape.url_escape(utf8(a), plus=False))\n        return self._path % tuple(converted_args)\n\nurl = URLSpec\n\n\nif hasattr(hmac, 'compare_digest'):  # python 3.3\n    _time_independent_equals = hmac.compare_digest\nelse:\n    def _time_independent_equals(a, b):\n        if len(a) != len(b):\n            return False\n        result = 0\n        if isinstance(a[0], int):  # python3 byte strings\n            for x, y in zip(a, b):\n                result |= x ^ y\n        else:  # python2\n            for x, y in zip(a, b):\n                result |= ord(x) ^ ord(y)\n        return result == 0\n\n\ndef create_signed_value(secret, name, value):\n    timestamp = utf8(str(int(time.time())))\n    value = base64.b64encode(utf8(value))\n    signature = _create_signature(secret, name, value, timestamp)\n    value = b\"|\".join([value, timestamp, signature])\n    return value\n\n\ndef decode_signed_value(secret, name, value, max_age_days=31):\n    if not value:\n        return None\n    parts = utf8(value).split(b\"|\")\n    if len(parts) != 3:\n        return None\n    signature = _create_signature(secret, name, parts[0], parts[1])\n    if not _time_independent_equals(parts[2], signature):\n        gen_log.warning(\"Invalid cookie signature %r\", value)\n        return None\n    timestamp = int(parts[1])\n    if timestamp < time.time() - max_age_days * 86400:\n        gen_log.warning(\"Expired cookie %r\", value)\n        return None\n    if timestamp > time.time() + 31 * 86400:\n        # _cookie_signature does not hash a delimiter between the\n        # parts of the cookie, so an attacker could transfer trailing\n        # digits from the payload to the timestamp without altering the\n        # signature.  For backwards compatibility, sanity-check timestamp\n        # here instead of modifying _cookie_signature.\n        gen_log.warning(\"Cookie timestamp in future; possible tampering %r\", value)\n        return None\n    if parts[1].startswith(b\"0\"):\n        gen_log.warning(\"Tampered cookie %r\", value)\n        return None\n    try:\n        return base64.b64decode(parts[0])\n    except Exception:\n        return None\n\n\ndef _create_signature(secret, *parts):\n    hash = hmac.new(utf8(secret), digestmod=hashlib.sha1)\n    for part in parts:\n        hash.update(utf8(part))\n    return utf8(hash.hexdigest())\n"}
A user will ask you to solve a task. You should first draft your thinking process (inner monologue). Then, generate the solution.

Your response format must follow the template below:
<think>
Your thoughts or/and draft, like working through an exercise on scratch paper. Be as casual and as long as you want until you are confident to generate a correct solution.
</think>
<solution>
Final solution presented to the user.
</solution>
system
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** `current_user` in UI modules is not lazily evaluated

**Description:**
When using `current_user` within UI modules, it is evaluated immediately during the module's initialization rather than being accessed lazily. This premature evaluation can lead to unexpected behavior, such as unnecessary database queries or incorrect user data being loaded before it's needed.

**Example Buggy Code:**
```python
class UserProfileModule(UIModule):
    def render(self):
        user = self.current_user  # This triggers get_current_user immediately
        if user:
            return f"Hello, {user.name}!"
        return "Hello, Guest!"
```

In the above example, accessing `self.current_user` during the `render` method causes the `get_current_user` method to be called immediately, which may not be desirable in all contexts.

**Expected Behavior:**
The `current_user` property should be accessed lazily, meaning `get_current_user` is called only when `current_user` is explicitly accessed within the UI module. This ensures that user data is loaded only when necessary, improving performance and preventing unintended side effects.

**Actual Behavior:**
`current_user` is evaluated eagerly during the initialization of the UI module, leading to premature calls to `get_current_user`. This results in unnecessary processing and potential inconsistencies in user data handling.

[/ISSUE]
--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.

--- BEGIN FILE ---
```
### tornado/web.py
#!/usr/bin/env python
#
# Copyright 2009 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

"""``tornado.web`` provides a simple web framework with asynchronous
features that allow it to scale to large numbers of open connections,
making it ideal for `long polling
<http://en.wikipedia.org/wiki/Push_technology#Long_polling>`_.

Here is a simple "Hello, world" example app::

    import tornado.ioloop
    import tornado.web

    class MainHandler(tornado.web.RequestHandler):
        def get(self):
            self.write("Hello, world")

    if __name__ == "__main__":
        application = tornado.web.Application([
            (r"/", MainHandler),
        ])
        application.listen(8888)
        tornado.ioloop.IOLoop.instance().start()

See the :doc:`Tornado overview <overview>` for more details and a good getting
started guide.

Thread-safety notes
-------------------

In general, methods on `RequestHandler` and elsewhere in Tornado are
not thread-safe.  In particular, methods such as
`~RequestHandler.write()`, `~RequestHandler.finish()`, and
`~RequestHandler.flush()` must only be called from the main thread.  If
you use multiple threads it is important to use `.IOLoop.add_callback`
to transfer control back to the main thread before finishing the
request.
"""

from __future__ import absolute_import, division, print_function, with_statement


import base64
import binascii
import datetime
import email.utils
import functools
import gzip
import hashlib
import hmac
import mimetypes
import numbers
import os.path
import re
import stat
import sys
import threading
import time
import tornado
import traceback
import types
import uuid

from tornado.concurrent import Future
from tornado import escape
from tornado import httputil
from tornado import locale
from tornado.log import access_log, app_log, gen_log
from tornado import stack_context
from tornado import template
from tornado.escape import utf8, _unicode
from tornado.util import bytes_type, import_object, ObjectDict, raise_exc_info, unicode_type

try:
    from io import BytesIO  # python 3
except ImportError:
    from cStringIO import StringIO as BytesIO  # python 2

try:
    import Cookie  # py2
except ImportError:
    import http.cookies as Cookie  # py3

try:
    import urlparse  # py2
except ImportError:
    import urllib.parse as urlparse  # py3

try:
    from urllib import urlencode  # py2
except ImportError:
    from urllib.parse import urlencode  # py3


class RequestHandler(object):
    """Subclass this class and define `get()` or `post()` to make a handler.

    If you want to support more methods than the standard GET/HEAD/POST, you
    should override the class variable ``SUPPORTED_METHODS`` in your
    `RequestHandler` subclass.
    """
    SUPPORTED_METHODS = ("GET", "HEAD", "POST", "DELETE", "PATCH", "PUT",
                         "OPTIONS")

    _template_loaders = {}  # {path: template.BaseLoader}
    _template_loader_lock = threading.Lock()
    _remove_control_chars_regex = re.compile(r"[\x00-\x08\x0e-\x1f]")

    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)

    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

    @property
    def settings(self):
        """An alias for `self.application.settings <Application.settings>`."""
        return self.application.settings

    def head(self, *args, **kwargs):
        raise HTTPError(405)

    def get(self, *args, **kwargs):
        raise HTTPError(405)

    def post(self, *args, **kwargs):
        raise HTTPError(405)

    def delete(self, *args, **kwargs):
        raise HTTPError(405)

    def patch(self, *args, **kwargs):
        raise HTTPError(405)

    def put(self, *args, **kwargs):
        raise HTTPError(405)

    def options(self, *args, **kwargs):
        raise HTTPError(405)

    def prepare(self):
        """Called at the beginning of a request before  `get`/`post`/etc.

        Override this method to perform common initialization regardless
        of the request method.

        Asynchronous support: Decorate this method with `.gen.coroutine`
        or `.return_future` to make it asynchronous (the
        `asynchronous` decorator cannot be used on `prepare`).
        If this method returns a `.Future` execution will not proceed
        until the `.Future` is done.

        .. versionadded:: 3.1
           Asynchronous support.
        """
        pass

    def on_finish(self):
        """Called after the end of a request.

        Override this method to perform cleanup, logging, etc.
        This method is a counterpart to `prepare`.  ``on_finish`` may
        not produce any output, as it is called after the response
        has been sent to the client.
        """
        pass

    def on_connection_close(self):
        """Called in async handlers if the client closed the connection.

        Override this to clean up resources associated with
        long-lived connections.  Note that this method is called only if
        the connection was closed during asynchronous processing; if you
        need to do cleanup after every request override `on_finish`
        instead.

        Proxies may keep a connection open for a time (perhaps
        indefinitely) after the client has gone away, so this method
        may not be called promptly after the end user closes their
        connection.
        """
        pass

    def clear(self):
        """Resets all headers and content for this response."""
        self._headers = httputil.HTTPHeaders({
            "Server": "TornadoServer/%s" % tornado.version,
            "Content-Type": "text/html; charset=UTF-8",
            "Date": httputil.format_timestamp(time.time()),
        })
        self.set_default_headers()
        if (not self.request.supports_http_1_1() and
            getattr(self.request, 'connection', None) and
                not self.request.connection.no_keep_alive):
            conn_header = self.request.headers.get("Connection")
            if conn_header and (conn_header.lower() == "keep-alive"):
                self.set_header("Connection", "Keep-Alive")
        self._write_buffer = []
        self._status_code = 200
        self._reason = httputil.responses[200]

    def set_default_headers(self):
        """Override this to set HTTP headers at the beginning of the request.

        For example, this is the place to set a custom ``Server`` header.
        Note that setting such headers in the normal flow of request
        processing may not do what you want, since headers may be reset
        during error handling.
        """
        pass

    def set_status(self, status_code, reason=None):
        """Sets the status code for our response.

        :arg int status_code: Response status code. If ``reason`` is ``None``,
            it must be present in `httplib.responses <http.client.responses>`.
        :arg string reason: Human-readable reason phrase describing the status
            code. If ``None``, it will be filled in from
            `httplib.responses <http.client.responses>`.
        """
        self._status_code = status_code
        if reason is not None:
            self._reason = escape.native_str(reason)
        else:
            try:
                self._reason = httputil.responses[status_code]
            except KeyError:
                raise ValueError("unknown status code %d", status_code)

    def get_status(self):
        """Returns the status code for our response."""
        return self._status_code

    def set_header(self, name, value):
        """Sets the given response header name and value.

        If a datetime is given, we automatically format it according to the
        HTTP specification. If the value is not a string, we convert it to
        a string. All header values are then encoded as UTF-8.
        """
        self._headers[name] = self._convert_header_value(value)

    def add_header(self, name, value):
        """Adds the given response header and value.

        Unlike `set_header`, `add_header` may be called multiple times
        to return multiple values for the same header.
        """
        self._headers.add(name, self._convert_header_value(value))

    def clear_header(self, name):
        """Clears an outgoing header, undoing a previous `set_header` call.

        Note that this method does not apply to multi-valued headers
        set by `add_header`.
        """
        if name in self._headers:
            del self._headers[name]

    _INVALID_HEADER_CHAR_RE = re.compile(br"[\x00-\x1f]")

    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

    _ARG_DEFAULT = []

    def get_argument(self, name, default=_ARG_DEFAULT, strip=True):
        """Returns the value of the argument with the given name.

        If default is not provided, the argument is considered to be
        required, and we raise a `MissingArgumentError` if it is missing.

        If the argument appears in the url more than once, we return the
        last value.

        The returned value is always unicode.
        """
        args = self.get_arguments(name, strip=strip)
        if not args:
            if default is self._ARG_DEFAULT:
                raise MissingArgumentError(name)
            return default
        return args[-1]

    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

    def decode_argument(self, value, name=None):
        """Decodes an argument from the request.

        The argument has been percent-decoded and is now a byte string.
        By default, this method decodes the argument as utf-8 and returns
        a unicode string, but this may be overridden in subclasses.

        This method is used as a filter for both `get_argument()` and for
        values extracted from the url and passed to `get()`/`post()`/etc.

        The name of the argument is provided if known, but may be None
        (e.g. for unnamed groups in the url regex).
        """
        return _unicode(value)

    @property
    def cookies(self):
        """An alias for `self.request.cookies <.httpserver.HTTPRequest.cookies>`."""
        return self.request.cookies

    def get_cookie(self, name, default=None):
        """Gets the value of the cookie with the given name, else default."""
        if self.request.cookies is not None and name in self.request.cookies:
            return self.request.cookies[name].value
        return default

    def set_cookie(self, name, value, domain=None, expires=None, path="/",
                   expires_days=None, **kwargs):
        """Sets the given cookie name/value with the given options.

        Additional keyword arguments are set on the Cookie.Morsel
        directly.
        See http://docs.python.org/library/cookie.html#morsel-objects
        for available attributes.
        """
        # The cookie library only accepts type str, in both python 2 and 3
        name = escape.native_str(name)
        value = escape.native_str(value)
        if re.search(r"[\x00-\x20]", name + value):
            # Don't let us accidentally inject bad stuff
            raise ValueError("Invalid cookie %r: %r" % (name, value))
        if not hasattr(self, "_new_cookie"):
            self._new_cookie = Cookie.SimpleCookie()
        if name in self._new_cookie:
            del self._new_cookie[name]
        self._new_cookie[name] = value
        morsel = self._new_cookie[name]
        if domain:
            morsel["domain"] = domain
        if expires_days is not None and not expires:
            expires = datetime.datetime.utcnow() + datetime.timedelta(
                days=expires_days)
        if expires:
            morsel["expires"] = httputil.format_timestamp(expires)
        if path:
            morsel["path"] = path
        for k, v in kwargs.items():
            if k == 'max_age':
                k = 'max-age'
            morsel[k] = v

    def clear_cookie(self, name, path="/", domain=None):
        """Deletes the cookie with the given name."""
        expires = datetime.datetime.utcnow() - datetime.timedelta(days=365)
        self.set_cookie(name, value="", path=path, expires=expires,
                        domain=domain)

    def clear_all_cookies(self):
        """Deletes all the cookies the user sent with this request."""
        for name in self.request.cookies:
            self.clear_cookie(name)

    def set_secure_cookie(self, name, value, expires_days=30, **kwargs):
        """Signs and timestamps a cookie so it cannot be forged.

        You must specify the ``cookie_secret`` setting in your Application
        to use this method. It should be a long, random sequence of bytes
        to be used as the HMAC secret for the signature.

        To read a cookie set with this method, use `get_secure_cookie()`.

        Note that the ``expires_days`` parameter sets the lifetime of the
        cookie in the browser, but is independent of the ``max_age_days``
        parameter to `get_secure_cookie`.

        Secure cookies may contain arbitrary byte values, not just unicode
        strings (unlike regular cookies)
        """
        self.set_cookie(name, self.create_signed_value(name, value),
                        expires_days=expires_days, **kwargs)

    def create_signed_value(self, name, value):
        """Signs and timestamps a string so it cannot be forged.

        Normally used via set_secure_cookie, but provided as a separate
        method for non-cookie uses.  To decode a value not stored
        as a cookie use the optional value argument to get_secure_cookie.
        """
        self.require_setting("cookie_secret", "secure cookies")
        return create_signed_value(self.application.settings["cookie_secret"],
                                   name, value)

    def get_secure_cookie(self, name, value=None, max_age_days=31):
        """Returns the given signed cookie if it validates, or None.

        The decoded cookie value is returned as a byte string (unlike
        `get_cookie`).
        """
        self.require_setting("cookie_secret", "secure cookies")
        if value is None:
            value = self.get_cookie(name)
        return decode_signed_value(self.application.settings["cookie_secret"],
                                   name, value, max_age_days=max_age_days)

    def redirect(self, url, permanent=False, status=None):
        """Sends a redirect to the given (optionally relative) URL.

        If the ``status`` argument is specified, that value is used as the
        HTTP status code; otherwise either 301 (permanent) or 302
        (temporary) is chosen based on the ``permanent`` argument.
        The default is 302 (temporary).
        """
        if self._headers_written:
            raise Exception("Cannot redirect after headers have been written")
        if status is None:
            status = 301 if permanent else 302
        else:
            assert isinstance(status, int) and 300 <= status <= 399
        self.set_status(status)
        self.set_header("Location", urlparse.urljoin(utf8(self.request.uri),
                                                     utf8(url)))
        self.finish()

    def write(self, chunk):
        """Writes the given chunk to the output buffer.

        To write the output to the network, use the flush() method below.

        If the given chunk is a dictionary, we write it as JSON and set
        the Content-Type of the response to be ``application/json``.
        (if you want to send JSON as a different ``Content-Type``, call
        set_header *after* calling write()).

        Note that lists are not converted to JSON because of a potential
        cross-site security vulnerability.  All JSON output should be
        wrapped in a dictionary.  More details at
        http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
        """
        if self._finished:
            raise RuntimeError("Cannot write() after finish().  May be caused "
                               "by using async operations without the "
                               "@asynchronous decorator.")
        if isinstance(chunk, dict):
            chunk = escape.json_encode(chunk)
            self.set_header("Content-Type", "application/json; charset=UTF-8")
        chunk = utf8(chunk)
        self._write_buffer.append(chunk)

    def render(self, template_name, **kwargs):
        """Renders the template with the given arguments as the response."""
        html = self.render_string(template_name, **kwargs)

        # Insert the additional JS and CSS added by the modules on the page
        js_embed = []
        js_files = []
        css_embed = []
        css_files = []
        html_heads = []
        html_bodies = []
        for module in getattr(self, "_active_modules", {}).values():
            embed_part = module.embedded_javascript()
            if embed_part:
                js_embed.append(utf8(embed_part))
            file_part = module.javascript_files()
            if file_part:
                if isinstance(file_part, (unicode_type, bytes_type)):
                    js_files.append(file_part)
                else:
                    js_files.extend(file_part)
            embed_part = module.embedded_css()
            if embed_part:
                css_embed.append(utf8(embed_part))
            file_part = module.css_files()
            if file_part:
                if isinstance(file_part, (unicode_type, bytes_type)):
                    css_files.append(file_part)
                else:
                    css_files.extend(file_part)
            head_part = module.html_head()
            if head_part:
                html_heads.append(utf8(head_part))
            body_part = module.html_body()
            if body_part:
                html_bodies.append(utf8(body_part))

        def is_absolute(path):
            return any(path.startswith(x) for x in ["/", "http:", "https:"])
        if js_files:
            # Maintain order of JavaScript files given by modules
            paths = []
            unique_paths = set()
            for path in js_files:
                if not is_absolute(path):
                    path = self.static_url(path)
                if path not in unique_paths:
                    paths.append(path)
                    unique_paths.add(path)
            js = ''.join('<script src="' + escape.xhtml_escape(p) +
                         '" type="text/javascript"></script>'
                         for p in paths)
            sloc = html.rindex(b'</body>')
            html = html[:sloc] + utf8(js) + b'\n' + html[sloc:]
        if js_embed:
            js = b'<script type="text/javascript">\n//<![CDATA[\n' + \
                b'\n'.join(js_embed) + b'\n//]]>\n</script>'
            sloc = html.rindex(b'</body>')
            html = html[:sloc] + js + b'\n' + html[sloc:]
        if css_files:
            paths = []
            unique_paths = set()
            for path in css_files:
                if not is_absolute(path):
                    path = self.static_url(path)
                if path not in unique_paths:
                    paths.append(path)
                    unique_paths.add(path)
            css = ''.join('<link href="' + escape.xhtml_escape(p) + '" '
                          'type="text/css" rel="stylesheet"/>'
                          for p in paths)
            hloc = html.index(b'</head>')
            html = html[:hloc] + utf8(css) + b'\n' + html[hloc:]
        if css_embed:
            css = b'<style type="text/css">\n' + b'\n'.join(css_embed) + \
                b'\n</style>'
            hloc = html.index(b'</head>')
            html = html[:hloc] + css + b'\n' + html[hloc:]
        if html_heads:
            hloc = html.index(b'</head>')
            html = html[:hloc] + b''.join(html_heads) + b'\n' + html[hloc:]
        if html_bodies:
            hloc = html.index(b'</body>')
            html = html[:hloc] + b''.join(html_bodies) + b'\n' + html[hloc:]
        self.finish(html)

    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)

    def get_template_namespace(self):
        """Returns a dictionary to be used as the default template namespace.

        May be overridden by subclasses to add or modify values.

        The results of this method will be combined with additional
        defaults in the `tornado.template` module and keyword arguments
        to `render` or `render_string`.
        """
        namespace = dict(
            handler=self,
            request=self.request,
            current_user=self.current_user,
            locale=self.locale,
            _=self.locale.translate,
            static_url=self.static_url,
            xsrf_form_html=self.xsrf_form_html,
            reverse_url=self.reverse_url
        )
        namespace.update(self.ui)
        return namespace

    def create_template_loader(self, template_path):
        """Returns a new template loader for the given path.

        May be overridden by subclasses.  By default returns a
        directory-based loader on the given path, using the
        ``autoescape`` application setting.  If a ``template_loader``
        application setting is supplied, uses that instead.
        """
        settings = self.application.settings
        if "template_loader" in settings:
            return settings["template_loader"]
        kwargs = {}
        if "autoescape" in settings:
            # autoescape=None means "no escaping", so we have to be sure
            # to only pass this kwarg if the user asked for it.
            kwargs["autoescape"] = settings["autoescape"]
        return template.Loader(template_path, **kwargs)

    def flush(self, include_footers=False, callback=None):
        """Flushes the current output buffer to the network.

        The ``callback`` argument, if given, can be used for flow control:
        it will be run when all flushed data has been written to the socket.
        Note that only one flush callback can be outstanding at a time;
        if another flush occurs before the previous flush's callback
        has been run, the previous callback will be discarded.
        """
        if self.application._wsgi:
            # WSGI applications cannot usefully support flush, so just make
            # it a no-op (and run the callback immediately).
            if callback is not None:
                callback()
            return

        chunk = b"".join(self._write_buffer)
        self._write_buffer = []
        if not self._headers_written:
            self._headers_written = True
            for transform in self._transforms:
                self._status_code, self._headers, chunk = \
                    transform.transform_first_chunk(
                        self._status_code, self._headers, chunk, include_footers)
            headers = self._generate_headers()
        else:
            for transform in self._transforms:
                chunk = transform.transform_chunk(chunk, include_footers)
            headers = b""

        # Ignore the chunk and only write the headers for HEAD requests
        if self.request.method == "HEAD":
            if headers:
                self.request.write(headers, callback=callback)
            return

        self.request.write(headers + chunk, callback=callback)

    def finish(self, chunk=None):
        """Finishes this response, ending the HTTP request."""
        if self._finished:
            raise RuntimeError("finish() called twice.  May be caused "
                               "by using async operations without the "
                               "@asynchronous decorator.")

        if chunk is not None:
            self.write(chunk)

        # Automatically support ETags and add the Content-Length header if
        # we have not flushed any content yet.
        if not self._headers_written:
            if (self._status_code == 200 and
                self.request.method in ("GET", "HEAD") and
                    "Etag" not in self._headers):
                self.set_etag_header()
                if self.check_etag_header():
                    self._write_buffer = []
                    self.set_status(304)
            if self._status_code == 304:
                assert not self._write_buffer, "Cannot send body with 304"
                self._clear_headers_for_304()
            elif "Content-Length" not in self._headers:
                content_length = sum(len(part) for part in self._write_buffer)
                self.set_header("Content-Length", content_length)

        if hasattr(self.request, "connection"):
            # Now that the request is finished, clear the callback we
            # set on the IOStream (which would otherwise prevent the
            # garbage collection of the RequestHandler when there
            # are keepalive connections)
            self.request.connection.stream.set_close_callback(None)

        if not self.application._wsgi:
            self.flush(include_footers=True)
            self.request.finish()
            self._log()
        self._finished = True
        self.on_finish()
        # Break up a reference cycle between this handler and the
        # _ui_module closures to allow for faster GC on CPython.
        self.ui = None

    def send_error(self, status_code=500, **kwargs):
        """Sends the given HTTP error code to the browser.

        If `flush()` has already been called, it is not possible to send
        an error, so this method will simply terminate the response.
        If output has been written but not yet flushed, it will be discarded
        and replaced with the error page.

        Override `write_error()` to customize the error page that is returned.
        Additional keyword arguments are passed through to `write_error`.
        """
        if self._headers_written:
            gen_log.error("Cannot send error response after headers written")
            if not self._finished:
                self.finish()
            return
        self.clear()

        reason = None
        if 'exc_info' in kwargs:
            exception = kwargs['exc_info'][1]
            if isinstance(exception, HTTPError) and exception.reason:
                reason = exception.reason
        self.set_status(status_code, reason=reason)
        try:
            self.write_error(status_code, **kwargs)
        except Exception:
            app_log.error("Uncaught exception in write_error", exc_info=True)
        if not self._finished:
            self.finish()

    def write_error(self, status_code, **kwargs):
        """Override to implement custom error pages.

        ``write_error`` may call `write`, `render`, `set_header`, etc
        to produce output as usual.

        If this error was caused by an uncaught exception (including
        HTTPError), an ``exc_info`` triple will be available as
        ``kwargs["exc_info"]``.  Note that this exception may not be
        the "current" exception for purposes of methods like
        ``sys.exc_info()`` or ``traceback.format_exc``.

        For historical reasons, if a method ``get_error_html`` exists,
        it will be used instead of the default ``write_error`` implementation.
        ``get_error_html`` returned a string instead of producing output
        normally, and had different semantics for exception handling.
        Users of ``get_error_html`` are encouraged to convert their code
        to override ``write_error`` instead.
        """
        if hasattr(self, 'get_error_html'):
            if 'exc_info' in kwargs:
                exc_info = kwargs.pop('exc_info')
                kwargs['exception'] = exc_info[1]
                try:
                    # Put the traceback into sys.exc_info()
                    raise_exc_info(exc_info)
                except Exception:
                    self.finish(self.get_error_html(status_code, **kwargs))
            else:
                self.finish(self.get_error_html(status_code, **kwargs))
            return
        if self.settings.get("debug") and "exc_info" in kwargs:
            # in debug mode, try to send a traceback
            self.set_header('Content-Type', 'text/plain')
            for line in traceback.format_exception(*kwargs["exc_info"]):
                self.write(line)
            self.finish()
        else:
            self.finish("<html><title>%(code)d: %(message)s</title>"
                        "<body>%(code)d: %(message)s</body></html>" % {
                            "code": status_code,
                            "message": self._reason,
                        })

    @property
    def locale(self):
        """The local for the current session.

        Determined by either `get_user_locale`, which you can override to
        set the locale based on, e.g., a user preference stored in a
        database, or `get_browser_locale`, which uses the ``Accept-Language``
        header.
        """
        if not hasattr(self, "_locale"):
            self._locale = self.get_user_locale()
            if not self._locale:
                self._locale = self.get_browser_locale()
                assert self._locale
        return self._locale

    def get_user_locale(self):
        """Override to determine the locale from the authenticated user.

        If None is returned, we fall back to `get_browser_locale()`.

        This method should return a `tornado.locale.Locale` object,
        most likely obtained via a call like ``tornado.locale.get("en")``
        """
        return None

    def get_browser_locale(self, default="en_US"):
        """Determines the user's locale from ``Accept-Language`` header.

        See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
        """
        if "Accept-Language" in self.request.headers:
            languages = self.request.headers["Accept-Language"].split(",")
            locales = []
            for language in languages:
                parts = language.strip().split(";")
                if len(parts) > 1 and parts[1].startswith("q="):
                    try:
                        score = float(parts[1][2:])
                    except (ValueError, TypeError):
                        score = 0.0
                else:
                    score = 1.0
                locales.append((parts[0], score))
            if locales:
                locales.sort(key=lambda pair: pair[1], reverse=True)
                codes = [l[0] for l in locales]
                return locale.get(*codes)
        return locale.get(default)

    @property
    def current_user(self):
        """The authenticated user for this request.

        This is a cached version of `get_current_user`, which you can
        override to set the user based on, e.g., a cookie. If that
        method is not overridden, this method always returns None.

        We lazy-load the current user the first time this method is called
        and cache the result after that.
        """
        if not hasattr(self, "_current_user"):
            self._current_user = self.get_current_user()
        return self._current_user

    @current_user.setter
    def current_user(self, value):
        self._current_user = value

    def get_current_user(self):
        """Override to determine the current user from, e.g., a cookie."""
        return None

    def get_login_url(self):
        """Override to customize the login URL based on the request.

        By default, we use the ``login_url`` application setting.
        """
        self.require_setting("login_url", "@tornado.web.authenticated")
        return self.application.settings["login_url"]

    def get_template_path(self):
        """Override to customize template path for each handler.

        By default, we use the ``template_path`` application setting.
        Return None to load templates relative to the calling file.
        """
        return self.application.settings.get("template_path")

    @property
    def xsrf_token(self):
        """The XSRF-prevention token for the current user/session.

        To prevent cross-site request forgery, we set an '_xsrf' cookie
        and include the same '_xsrf' value as an argument with all POST
        requests. If the two do not match, we reject the form submission
        as a potential forgery.

        See http://en.wikipedia.org/wiki/Cross-site_request_forgery
        """
        if not hasattr(self, "_xsrf_token"):
            token = self.get_cookie("_xsrf")
            if not token:
                token = binascii.b2a_hex(uuid.uuid4().bytes)
                expires_days = 30 if self.current_user else None
                self.set_cookie("_xsrf", token, expires_days=expires_days)
            self._xsrf_token = token
        return self._xsrf_token

    def check_xsrf_cookie(self):
        """Verifies that the ``_xsrf`` cookie matches the ``_xsrf`` argument.

        To prevent cross-site request forgery, we set an ``_xsrf``
        cookie and include the same value as a non-cookie
        field with all ``POST`` requests. If the two do not match, we
        reject the form submission as a potential forgery.

        The ``_xsrf`` value may be set as either a form field named ``_xsrf``
        or in a custom HTTP header named ``X-XSRFToken`` or ``X-CSRFToken``
        (the latter is accepted for compatibility with Django).

        See http://en.wikipedia.org/wiki/Cross-site_request_forgery

        Prior to release 1.1.1, this check was ignored if the HTTP header
        ``X-Requested-With: XMLHTTPRequest`` was present.  This exception
        has been shown to be insecure and has been removed.  For more
        information please see
        http://www.djangoproject.com/weblog/2011/feb/08/security/
        http://weblog.rubyonrails.org/2011/2/8/csrf-protection-bypass-in-ruby-on-rails
        """
        token = (self.get_argument("_xsrf", None) or
                 self.request.headers.get("X-Xsrftoken") or
                 self.request.headers.get("X-Csrftoken"))
        if not token:
            raise HTTPError(403, "'_xsrf' argument missing from POST")
        if self.xsrf_token != token:
            raise HTTPError(403, "XSRF cookie does not match POST argument")

    def xsrf_form_html(self):
        """An HTML ``<input/>`` element to be included with all POST forms.

        It defines the ``_xsrf`` input value, which we check on all POST
        requests to prevent cross-site request forgery. If you have set
        the ``xsrf_cookies`` application setting, you must include this
        HTML within all of your HTML forms.

        In a template, this method should be called with ``{% module
        xsrf_form_html() %}``

        See `check_xsrf_cookie()` above for more information.
        """
        return '<input type="hidden" name="_xsrf" value="' + \
            escape.xhtml_escape(self.xsrf_token) + '"/>'

    def static_url(self, path, include_host=None, **kwargs):
        """Returns a static URL for the given relative static file path.

        This method requires you set the ``static_path`` setting in your
        application (which specifies the root directory of your static
        files).

        This method returns a versioned url (by default appending
        ``?v=<signature>``), which allows the static files to be
        cached indefinitely.  This can be disabled by passing
        ``include_version=False`` (in the default implementation;
        other static file implementations are not required to support
        this, but they may support other options).

        By default this method returns URLs relative to the current
        host, but if ``include_host`` is true the URL returned will be
        absolute.  If this handler has an ``include_host`` attribute,
        that value will be used as the default for all `static_url`
        calls that do not pass ``include_host`` as a keyword argument.

        """
        self.require_setting("static_path", "static_url")
        get_url = self.settings.get("static_handler_class",
                                    StaticFileHandler).make_static_url

        if include_host is None:
            include_host = getattr(self, "include_host", False)

        if include_host:
            base = self.request.protocol + "://" + self.request.host
        else:
            base = ""

        return base + get_url(self.settings, path, **kwargs)

    def async_callback(self, callback, *args, **kwargs):
        """Obsolete - catches exceptions from the wrapped function.

        This function is unnecessary since Tornado 1.1.
        """
        if callback is None:
            return None
        if args or kwargs:
            callback = functools.partial(callback, *args, **kwargs)

        def wrapper(*args, **kwargs):
            try:
                return callback(*args, **kwargs)
            except Exception as e:
                if self._headers_written:
                    app_log.error("Exception after headers written",
                                  exc_info=True)
                else:
                    self._handle_request_exception(e)
        return wrapper

    def require_setting(self, name, feature="this feature"):
        """Raises an exception if the given app setting is not defined."""
        if not self.application.settings.get(name):
            raise Exception("You must define the '%s' setting in your "
                            "application to use %s" % (name, feature))

    def reverse_url(self, name, *args):
        """Alias for `Application.reverse_url`."""
        return self.application.reverse_url(name, *args)

    def compute_etag(self):
        """Computes the etag header to be used for this request.

        By default uses a hash of the content written so far.

        May be overridden to provide custom etag implementations,
        or may return None to disable tornado's default etag support.
        """
        hasher = hashlib.sha1()
        for part in self._write_buffer:
            hasher.update(part)
        return '"%s"' % hasher.hexdigest()

    def set_etag_header(self):
        """Sets the response's Etag header using ``self.compute_etag()``.

        Note: no header will be set if ``compute_etag()`` returns ``None``.

        This method is called automatically when the request is finished.
        """
        etag = self.compute_etag()
        if etag is not None:
            self.set_header("Etag", etag)

    def check_etag_header(self):
        """Checks the ``Etag`` header against requests's ``If-None-Match``.

        Returns ``True`` if the request's Etag matches and a 304 should be
        returned. For example::

            self.set_etag_header()
            if self.check_etag_header():
                self.set_status(304)
                return

        This method is called automatically when the request is finished,
        but may be called earlier for applications that override
        `compute_etag` and want to do an early check for ``If-None-Match``
        before completing the request.  The ``Etag`` header should be set
        (perhaps with `set_etag_header`) before calling this method.
        """
        etag = self._headers.get("Etag")
        inm = utf8(self.request.headers.get("If-None-Match", ""))
        return bool(etag and inm and inm.find(etag) >= 0)

    def _stack_context_handle_exception(self, type, value, traceback):
        try:
            # For historical reasons _handle_request_exception only takes
            # the exception value instead of the full triple,
            # so re-raise the exception to ensure that it's in
            # sys.exc_info()
            raise_exc_info((type, value, traceback))
        except Exception:
            self._handle_request_exception(value)
        return True

    def _execute(self, transforms, *args, **kwargs):
        """Executes this request with the given output transforms."""
        self._transforms = transforms
        try:
            if self.request.method not in self.SUPPORTED_METHODS:
                raise HTTPError(405)
            self.path_args = [self.decode_argument(arg) for arg in args]
            self.path_kwargs = dict((k, self.decode_argument(v, name=k))
                                    for (k, v) in kwargs.items())
            # If XSRF cookies are turned on, reject form submissions without
            # the proper cookie
            if self.request.method not in ("GET", "HEAD", "OPTIONS") and \
                    self.application.settings.get("xsrf_cookies"):
                self.check_xsrf_cookie()
            self._when_complete(self.prepare(), self._execute_method)
        except Exception as e:
            self._handle_request_exception(e)

    def _when_complete(self, result, callback):
        try:
            if result is None:
                callback()
            elif isinstance(result, Future):
                if result.done():
                    if result.result() is not None:
                        raise ValueError('Expected None, got %r' % result.result())
                    callback()
                else:
                    # Delayed import of IOLoop because it's not available
                    # on app engine
                    from tornado.ioloop import IOLoop
                    IOLoop.current().add_future(
                        result, functools.partial(self._when_complete,
                                                  callback=callback))
            else:
                raise ValueError("Expected Future or None, got %r" % result)
        except Exception as e:
            self._handle_request_exception(e)

    def _execute_method(self):
        if not self._finished:
            method = getattr(self, self.request.method.lower())
            self._when_complete(method(*self.path_args, **self.path_kwargs),
                                self._execute_finish)

    def _execute_finish(self):
        if self._auto_finish and not self._finished:
            self.finish()

    def _generate_headers(self):
        reason = self._reason
        lines = [utf8(self.request.version + " " +
                      str(self._status_code) +
                      " " + reason)]
        lines.extend([utf8(n) + b": " + utf8(v) for n, v in self._headers.get_all()])

        if hasattr(self, "_new_cookie"):
            for cookie in self._new_cookie.values():
                lines.append(utf8("Set-Cookie: " + cookie.OutputString(None)))
        return b"\r\n".join(lines) + b"\r\n\r\n"

    def _log(self):
        """Logs the current request.

        Sort of deprecated since this functionality was moved to the
        Application, but left in place for the benefit of existing apps
        that have overridden this method.
        """
        self.application.log_request(self)

    def _request_summary(self):
        return self.request.method + " " + self.request.uri + \
            " (" + self.request.remote_ip + ")"

    def _handle_request_exception(self, e):
        self.log_exception(*sys.exc_info())
        if self._finished:
            # Extra errors after the request has been finished should
            # be logged, but there is no reason to continue to try and
            # send a response.
            return
        if isinstance(e, HTTPError):
            if e.status_code not in httputil.responses and not e.reason:
                gen_log.error("Bad HTTP status code: %d", e.status_code)
                self.send_error(500, exc_info=sys.exc_info())
            else:
                self.send_error(e.status_code, exc_info=sys.exc_info())
        else:
            self.send_error(500, exc_info=sys.exc_info())

    def log_exception(self, typ, value, tb):
        """Override to customize logging of uncaught exceptions.

        By default logs instances of `HTTPError` as warnings without
        stack traces (on the ``tornado.general`` logger), and all
        other exceptions as errors with stack traces (on the
        ``tornado.application`` logger).

        .. versionadded:: 3.1
        """
        if isinstance(value, HTTPError):
            if value.log_message:
                format = "%d %s: " + value.log_message
                args = ([value.status_code, self._request_summary()] +
                        list(value.args))
                gen_log.warning(format, *args)
        else:
            app_log.error("Uncaught exception %s\n%r", self._request_summary(),
                          self.request, exc_info=(typ, value, tb))

    def _ui_module(self, name, module):
        def render(*args, **kwargs):
            if not hasattr(self, "_active_modules"):
                self._active_modules = {}
            if name not in self._active_modules:
                self._active_modules[name] = module(self)
            rendered = self._active_modules[name].render(*args, **kwargs)
            return rendered
        return render

    def _ui_method(self, method):
        return lambda *args, **kwargs: method(self, *args, **kwargs)

    def _clear_headers_for_304(self):
        # 304 responses should not contain entity headers (defined in
        # http://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html#sec7.1)
        # not explicitly allowed by
        # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5
        headers = ["Allow", "Content-Encoding", "Content-Language",
                   "Content-Length", "Content-MD5", "Content-Range",
                   "Content-Type", "Last-Modified"]
        for h in headers:
            self.clear_header(h)


def asynchronous(method):
    """Wrap request handler methods with this if they are asynchronous.

    This decorator is unnecessary if the method is also decorated with
    ``@gen.coroutine`` (it is legal but unnecessary to use the two
    decorators together, in which case ``@asynchronous`` must be
    first).

    This decorator should only be applied to the :ref:`HTTP verb
    methods <verbs>`; its behavior is undefined for any other method.
    This decorator does not *make* a method asynchronous; it tells
    the framework that the method *is* asynchronous.  For this decorator
    to be useful the method must (at least sometimes) do something
    asynchronous.

    If this decorator is given, the response is not finished when the
    method returns. It is up to the request handler to call
    `self.finish() <RequestHandler.finish>` to finish the HTTP
    request. Without this decorator, the request is automatically
    finished when the ``get()`` or ``post()`` method returns. Example::

       class MyRequestHandler(web.RequestHandler):
           @web.asynchronous
           def get(self):
              http = httpclient.AsyncHTTPClient()
              http.fetch("http://friendfeed.com/", self._on_download)

           def _on_download(self, response):
              self.write("Downloaded!")
              self.finish()

    .. versionadded:: 3.1
       The ability to use ``@gen.coroutine`` without ``@asynchronous``.
    """
    # Delay the IOLoop import because it's not available on app engine.
    from tornado.ioloop import IOLoop
    @functools.wraps(method)
    def wrapper(self, *args, **kwargs):
        if self.application._wsgi:
            raise Exception("@asynchronous is not supported for WSGI apps")
        self._auto_finish = False
        with stack_context.ExceptionStackContext(
                self._stack_context_handle_exception):
            result = method(self, *args, **kwargs)
            if isinstance(result, Future):
                # If @asynchronous is used with @gen.coroutine, (but
                # not @gen.engine), we can automatically finish the
                # request when the future resolves.  Additionally,
                # the Future will swallow any exceptions so we need
                # to throw them back out to the stack context to finish
                # the request.
                def future_complete(f):
                    f.result()
                    if not self._finished:
                        self.finish()
                IOLoop.current().add_future(result, future_complete)
            return result
    return wrapper


def removeslash(method):
    """Use this decorator to remove trailing slashes from the request path.

    For example, a request to ``/foo/`` would redirect to ``/foo`` with this
    decorator. Your request handler mapping should use a regular expression
    like ``r'/foo/*'`` in conjunction with using the decorator.
    """
    @functools.wraps(method)
    def wrapper(self, *args, **kwargs):
        if self.request.path.endswith("/"):
            if self.request.method in ("GET", "HEAD"):
                uri = self.request.path.rstrip("/")
                if uri:  # don't try to redirect '/' to ''
                    if self.request.query:
                        uri += "?" + self.request.query
                    self.redirect(uri, permanent=True)
                    return
            else:
                raise HTTPError(404)
        return method(self, *args, **kwargs)
    return wrapper


def addslash(method):
    """Use this decorator to add a missing trailing slash to the request path.

    For example, a request to ``/foo`` would redirect to ``/foo/`` with this
    decorator. Your request handler mapping should use a regular expression
    like ``r'/foo/?'`` in conjunction with using the decorator.
    """
    @functools.wraps(method)
    def wrapper(self, *args, **kwargs):
        if not self.request.path.endswith("/"):
            if self.request.method in ("GET", "HEAD"):
                uri = self.request.path + "/"
                if self.request.query:
                    uri += "?" + self.request.query
                self.redirect(uri, permanent=True)
                return
            raise HTTPError(404)
        return method(self, *args, **kwargs)
    return wrapper


class Application(object):
    """A collection of request handlers that make up a web application.

    Instances of this class are callable and can be passed directly to
    HTTPServer to serve the application::

        application = web.Application([
            (r"/", MainPageHandler),
        ])
        http_server = httpserver.HTTPServer(application)
        http_server.listen(8080)
        ioloop.IOLoop.instance().start()

    The constructor for this class takes in a list of `URLSpec` objects
    or (regexp, request_class) tuples. When we receive requests, we
    iterate over the list in order and instantiate an instance of the
    first request class whose regexp matches the request path.

    Each tuple can contain an optional third element, which should be
    a dictionary if it is present. That dictionary is passed as
    keyword arguments to the contructor of the handler. This pattern
    is used for the `StaticFileHandler` in this example (note that a
    `StaticFileHandler` can be installed automatically with the
    static_path setting described below)::

        application = web.Application([
            (r"/static/(.*)", web.StaticFileHandler, {"path": "/var/www"}),
        ])

    We support virtual hosts with the `add_handlers` method, which takes in
    a host regular expression as the first argument::

        application.add_handlers(r"www\.myhost\.com", [
            (r"/article/([0-9]+)", ArticleHandler),
        ])

    You can serve static files by sending the ``static_path`` setting
    as a keyword argument. We will serve those files from the
    ``/static/`` URI (this is configurable with the
    ``static_url_prefix`` setting), and we will serve ``/favicon.ico``
    and ``/robots.txt`` from the same directory.  A custom subclass of
    `StaticFileHandler` can be specified with the
    ``static_handler_class`` setting.
    """
    def __init__(self, handlers=None, default_host="", transforms=None,
                 wsgi=False, **settings):
        if transforms is None:
            self.transforms = []
            if settings.get("gzip"):
                self.transforms.append(GZipContentEncoding)
            self.transforms.append(ChunkedTransferEncoding)
        else:
            self.transforms = transforms
        self.handlers = []
        self.named_handlers = {}
        self.default_host = default_host
        self.settings = settings
        self.ui_modules = {'linkify': _linkify,
                           'xsrf_form_html': _xsrf_form_html,
                           'Template': TemplateModule,
                           }
        self.ui_methods = {}
        self._wsgi = wsgi
        self._load_ui_modules(settings.get("ui_modules", {}))
        self._load_ui_methods(settings.get("ui_methods", {}))
        if self.settings.get("static_path"):
            path = self.settings["static_path"]
            handlers = list(handlers or [])
            static_url_prefix = settings.get("static_url_prefix",
                                             "/static/")
            static_handler_class = settings.get("static_handler_class",
                                                StaticFileHandler)
            static_handler_args = settings.get("static_handler_args", {})
            static_handler_args['path'] = path
            for pattern in [re.escape(static_url_prefix) + r"(.*)",
                            r"/(favicon\.ico)", r"/(robots\.txt)"]:
                handlers.insert(0, (pattern, static_handler_class,
                                    static_handler_args))
        if handlers:
            self.add_handlers(".*$", handlers)

        # Automatically reload modified modules
        if self.settings.get("debug") and not wsgi:
            from tornado import autoreload
            autoreload.start()

    def listen(self, port, address="", **kwargs):
        """Starts an HTTP server for this application on the given port.

        This is a convenience alias for creating an `.HTTPServer`
        object and calling its listen method.  Keyword arguments not
        supported by `HTTPServer.listen <.TCPServer.listen>` are passed to the
        `.HTTPServer` constructor.  For advanced uses
        (e.g. multi-process mode), do not use this method; create an
        `.HTTPServer` and call its
        `.TCPServer.bind`/`.TCPServer.start` methods directly.

        Note that after calling this method you still need to call
        ``IOLoop.instance().start()`` to start the server.
        """
        # import is here rather than top level because HTTPServer
        # is not importable on appengine
        from tornado.httpserver import HTTPServer
        server = HTTPServer(self, **kwargs)
        server.listen(port, address)

    def add_handlers(self, host_pattern, host_handlers):
        """Appends the given handlers to our handler list.

        Host patterns are processed sequentially in the order they were
        added. All matching patterns will be considered.
        """
        if not host_pattern.endswith("$"):
            host_pattern += "$"
        handlers = []
        # The handlers with the wildcard host_pattern are a special
        # case - they're added in the constructor but should have lower
        # precedence than the more-precise handlers added later.
        # If a wildcard handler group exists, it should always be last
        # in the list, so insert new groups just before it.
        if self.handlers and self.handlers[-1][0].pattern == '.*$':
            self.handlers.insert(-1, (re.compile(host_pattern), handlers))
        else:
            self.handlers.append((re.compile(host_pattern), handlers))

        for spec in host_handlers:
            if isinstance(spec, (tuple, list)):
                assert len(spec) in (2, 3)
                pattern = spec[0]
                handler = spec[1]

                if isinstance(handler, str):
                    # import the Module and instantiate the class
                    # Must be a fully qualified name (module.ClassName)
                    handler = import_object(handler)

                if len(spec) == 3:
                    kwargs = spec[2]
                else:
                    kwargs = {}
                spec = URLSpec(pattern, handler, kwargs)
            handlers.append(spec)
            if spec.name:
                if spec.name in self.named_handlers:
                    app_log.warning(
                        "Multiple handlers named %s; replacing previous value",
                        spec.name)
                self.named_handlers[spec.name] = spec

    def add_transform(self, transform_class):
        self.transforms.append(transform_class)

    def _get_host_handlers(self, request):
        host = request.host.lower().split(':')[0]
        matches = []
        for pattern, handlers in self.handlers:
            if pattern.match(host):
                matches.extend(handlers)
        # Look for default host if not behind load balancer (for debugging)
        if not matches and "X-Real-Ip" not in request.headers:
            for pattern, handlers in self.handlers:
                if pattern.match(self.default_host):
                    matches.extend(handlers)
        return matches or None

    def _load_ui_methods(self, methods):
        if isinstance(methods, types.ModuleType):
            self._load_ui_methods(dict((n, getattr(methods, n))
                                       for n in dir(methods)))
        elif isinstance(methods, list):
            for m in methods:
                self._load_ui_methods(m)
        else:
            for name, fn in methods.items():
                if not name.startswith("_") and hasattr(fn, "__call__") \
                        and name[0].lower() == name[0]:
                    self.ui_methods[name] = fn

    def _load_ui_modules(self, modules):
        if isinstance(modules, types.ModuleType):
            self._load_ui_modules(dict((n, getattr(modules, n))
                                       for n in dir(modules)))
        elif isinstance(modules, list):
            for m in modules:
                self._load_ui_modules(m)
        else:
            assert isinstance(modules, dict)
            for name, cls in modules.items():
                try:
                    if issubclass(cls, UIModule):
                        self.ui_modules[name] = cls
                except TypeError:
                    pass

    def __call__(self, request):
        """Called by HTTPServer to execute the request."""
        transforms = [t(request) for t in self.transforms]
        handler = None
        args = []
        kwargs = {}
        handlers = self._get_host_handlers(request)
        if not handlers:
            handler = RedirectHandler(
                self, request, url="http://" + self.default_host + "/")
        else:
            for spec in handlers:
                match = spec.regex.match(request.path)
                if match:
                    handler = spec.handler_class(self, request, **spec.kwargs)
                    if spec.regex.groups:
                        # None-safe wrapper around url_unescape to handle
                        # unmatched optional groups correctly
                        def unquote(s):
                            if s is None:
                                return s
                            return escape.url_unescape(s, encoding=None,
                                                       plus=False)
                        # Pass matched groups to the handler.  Since
                        # match.groups() includes both named and unnamed groups,
                        # we want to use either groups or groupdict but not both.
                        # Note that args are passed as bytes so the handler can
                        # decide what encoding to use.

                        if spec.regex.groupindex:
                            kwargs = dict(
                                (str(k), unquote(v))
                                for (k, v) in match.groupdict().items())
                        else:
                            args = [unquote(s) for s in match.groups()]
                    break
            if not handler:
                handler = ErrorHandler(self, request, status_code=404)

        # In debug mode, re-compile templates and reload static files on every
        # request so you don't need to restart to see changes
        if self.settings.get("debug"):
            with RequestHandler._template_loader_lock:
                for loader in RequestHandler._template_loaders.values():
                    loader.reset()
            StaticFileHandler.reset()

        handler._execute(transforms, *args, **kwargs)
        return handler

    def reverse_url(self, name, *args):
        """Returns a URL path for handler named ``name``

        The handler must be added to the application as a named `URLSpec`.

        Args will be substituted for capturing groups in the `URLSpec` regex.
        They will be converted to strings if necessary, encoded as utf8,
        and url-escaped.
        """
        if name in self.named_handlers:
            return self.named_handlers[name].reverse(*args)
        raise KeyError("%s not found in named urls" % name)

    def log_request(self, handler):
        """Writes a completed HTTP request to the logs.

        By default writes to the python root logger.  To change
        this behavior either subclass Application and override this method,
        or pass a function in the application settings dictionary as
        ``log_function``.
        """
        if "log_function" in self.settings:
            self.settings["log_function"](handler)
            return
        if handler.get_status() < 400:
            log_method = access_log.info
        elif handler.get_status() < 500:
            log_method = access_log.warning
        else:
            log_method = access_log.error
        request_time = 1000.0 * handler.request.request_time()
        log_method("%d %s %.2fms", handler.get_status(),
                   handler._request_summary(), request_time)


class HTTPError(Exception):
    """An exception that will turn into an HTTP error response.

    Raising an `HTTPError` is a convenient alternative to calling
    `RequestHandler.send_error` since it automatically ends the
    current function.

    :arg int status_code: HTTP status code.  Must be listed in
        `httplib.responses <http.client.responses>` unless the ``reason``
        keyword argument is given.
    :arg string log_message: Message to be written to the log for this error
        (will not be shown to the user unless the `Application` is in debug
        mode).  May contain ``%s``-style placeholders, which will be filled
        in with remaining positional parameters.
    :arg string reason: Keyword-only argument.  The HTTP "reason" phrase
        to pass in the status line along with ``status_code``.  Normally
        determined automatically from ``status_code``, but can be used
        to use a non-standard numeric code.
    """
    def __init__(self, status_code, log_message=None, *args, **kwargs):
        self.status_code = status_code
        self.log_message = log_message
        self.args = args
        self.reason = kwargs.get('reason', None)

    def __str__(self):
        message = "HTTP %d: %s" % (
            self.status_code,
            self.reason or httputil.responses.get(self.status_code, 'Unknown'))
        if self.log_message:
            return message + " (" + (self.log_message % self.args) + ")"
        else:
            return message


class MissingArgumentError(HTTPError):
    """Exception raised by `RequestHandler.get_argument`.

    This is a subclass of `HTTPError`, so if it is uncaught a 400 response
    code will be used instead of 500 (and a stack trace will not be logged).

    .. versionadded:: 3.1
    """
    def __init__(self, arg_name):
        super(MissingArgumentError, self).__init__(
            400, 'Missing argument %s' % arg_name)
        self.arg_name = arg_name


class ErrorHandler(RequestHandler):
    """Generates an error response with ``status_code`` for all requests."""
    def initialize(self, status_code):
        self.set_status(status_code)

    def prepare(self):
        raise HTTPError(self._status_code)

    def check_xsrf_cookie(self):
        # POSTs to an ErrorHandler don't actually have side effects,
        # so we don't need to check the xsrf token.  This allows POSTs
        # to the wrong url to return a 404 instead of 403.
        pass


class RedirectHandler(RequestHandler):
    """Redirects the client to the given URL for all GET requests.

    You should provide the keyword argument ``url`` to the handler, e.g.::

        application = web.Application([
            (r"/oldpath", web.RedirectHandler, {"url": "/newpath"}),
        ])
    """
    def initialize(self, url, permanent=True):
        self._url = url
        self._permanent = permanent

    def get(self):
        self.redirect(self._url, permanent=self._permanent)


class StaticFileHandler(RequestHandler):
    """A simple handler that can serve static content from a directory.

    A `StaticFileHandler` is configured automatically if you pass the
    ``static_path`` keyword argument to `Application`.  This handler
    can be customized with the ``static_url_prefix``, ``static_handler_class``,
    and ``static_handler_args`` settings.

    To map an additional path to this handler for a static data directory
    you would add a line to your application like::

        application = web.Application([
            (r"/content/(.*)", web.StaticFileHandler, {"path": "/var/www"}),
        ])

    The handler constructor requires a ``path`` argument, which specifies the
    local root directory of the content to be served.

    Note that a capture group in the regex is required to parse the value for
    the ``path`` argument to the get() method (different than the constructor
    argument above); see `URLSpec` for details.

    To maximize the effectiveness of browser caching, this class supports
    versioned urls (by default using the argument ``?v=``).  If a version
    is given, we instruct the browser to cache this file indefinitely.
    `make_static_url` (also available as `RequestHandler.static_url`) can
    be used to construct a versioned url.

    This handler is intended primarily for use in development and light-duty
    file serving; for heavy traffic it will be more efficient to use
    a dedicated static file server (such as nginx or Apache).  We support
    the HTTP ``Accept-Ranges`` mechanism to return partial content (because
    some browsers require this functionality to be present to seek in
    HTML5 audio or video), but this handler should not be used with
    files that are too large to fit comfortably in memory.

    **Subclassing notes**

    This class is designed to be extensible by subclassing, but because
    of the way static urls are generated with class methods rather than
    instance methods, the inheritance patterns are somewhat unusual.
    Be sure to use the ``@classmethod`` decorator when overriding a
    class method.  Instance methods may use the attributes ``self.path``
    ``self.absolute_path``, and ``self.modified``.

    To change the way static urls are generated (e.g. to match the behavior
    of another server or CDN), override `make_static_url`, `parse_url_path`,
    `get_cache_time`, and/or `get_version`.

    To replace all interaction with the filesystem (e.g. to serve
    static content from a database), override `get_content`,
    `get_content_size`, `get_modified_time`, `get_absolute_path`, and
    `validate_absolute_path`.

    .. versionchanged:: 3.1
       Many of the methods for subclasses were added in Tornado 3.1.
    """
    CACHE_MAX_AGE = 86400 * 365 * 10  # 10 years

    _static_hashes = {}
    _lock = threading.Lock()  # protects _static_hashes

    def initialize(self, path, default_filename=None):
        self.root = path
        self.default_filename = default_filename

    @classmethod
    def reset(cls):
        with cls._lock:
            cls._static_hashes = {}

    def head(self, path):
        self.get(path, include_body=False)

    def get(self, path, include_body=True):
        # Set up our path instance variables.
        self.path = self.parse_url_path(path)
        del path  # make sure we don't refer to path instead of self.path again
        absolute_path = self.get_absolute_path(self.root, self.path)
        self.absolute_path = self.validate_absolute_path(
            self.root, absolute_path)
        if self.absolute_path is None:
            return

        self.modified = self.get_modified_time()
        self.set_headers()

        if self.should_return_304():
            self.set_status(304)
            return

        request_range = None
        range_header = self.request.headers.get("Range")
        if range_header:
            # As per RFC 2616 14.16, if an invalid Range header is specified,
            # the request will be treated as if the header didn't exist.
            request_range = httputil._parse_request_range(range_header)

        if request_range:
            start, end = request_range
            size = self.get_content_size()
            if (start is not None and start >= size) or end == 0:
                # As per RFC 2616 14.35.1, a range is not satisfiable only: if
                # the first requested byte is equal to or greater than the
                # content, or when a suffix with length 0 is specified
                self.set_status(416)  # Range Not Satisfiable
                self.set_header("Content-Type", "text/plain")
                self.set_header("Content-Range", "bytes */%s" %(size, ))
                return
            if start is not None and start < 0:
                start += size
            if end is not None and end > size:
                # Clients sometimes blindly use a large range to limit their
                # download size; cap the endpoint at the actual file size.
                end = size
            # Note: only return HTTP 206 if less than the entire range has been
            # requested. Not only is this semantically correct, but Chrome
            # refuses to play audio if it gets an HTTP 206 in response to
            # ``Range: bytes=0-``.
            if size != (end or size) - (start or 0):
                self.set_status(206)  # Partial Content
                self.set_header("Content-Range",
                                httputil._get_content_range(start, end, size))
        else:
            start = end = None
        content = self.get_content(self.absolute_path, start, end)
        if isinstance(content, bytes_type):
            content = [content]
        content_length = 0
        for chunk in content:
            if include_body:
                self.write(chunk)
            else:
                content_length += len(chunk)
        if not include_body:
            assert self.request.method == "HEAD"
            self.set_header("Content-Length", content_length)

    def compute_etag(self):
        """Sets the ``Etag`` header based on static url version.

        This allows efficient ``If-None-Match`` checks against cached
        versions, and sends the correct ``Etag`` for a partial response
        (i.e. the same ``Etag`` as the full file).

        .. versionadded:: 3.1
        """
        version_hash = self._get_cached_version(self.absolute_path)
        if not version_hash:
            return None
        return '"%s"' % (version_hash, )

    def set_headers(self):
        """Sets the content and caching headers on the response.

        .. versionadded:: 3.1
        """
        self.set_header("Accept-Ranges", "bytes")
        self.set_etag_header()

        if self.modified is not None:
            self.set_header("Last-Modified", self.modified)

        content_type = self.get_content_type()
        if content_type:
            self.set_header("Content-Type", content_type)

        cache_time = self.get_cache_time(self.path, self.modified, content_type)
        if cache_time > 0:
            self.set_header("Expires", datetime.datetime.utcnow() +
                            datetime.timedelta(seconds=cache_time))
            self.set_header("Cache-Control", "max-age=" + str(cache_time))

        self.set_extra_headers(self.path)

    def should_return_304(self):
        """Returns True if the headers indicate that we should return 304.

        .. versionadded:: 3.1
        """
        if self.check_etag_header():
            return True

        # Check the If-Modified-Since, and don't send the result if the
        # content has not been modified
        ims_value = self.request.headers.get("If-Modified-Since")
        if ims_value is not None:
            date_tuple = email.utils.parsedate(ims_value)
            if date_tuple is not None:
                if_since = datetime.datetime(*date_tuple[:6])
                if if_since >= self.modified:
                    return True

        return False

    @classmethod
    def get_absolute_path(cls, root, path):
        """Returns the absolute location of ``path`` relative to ``root``.

        ``root`` is the path configured for this `StaticFileHandler`
        (in most cases the ``static_path`` `Application` setting).

        This class method may be overridden in subclasses.  By default
        it returns a filesystem path, but other strings may be used
        as long as they are unique and understood by the subclass's
        overridden `get_content`.

        .. versionadded:: 3.1
        """
        abspath = os.path.abspath(os.path.join(root, path))
        return abspath

    def validate_absolute_path(self, root, absolute_path):
        """Validate and return the absolute path.

        ``root`` is the configured path for the `StaticFileHandler`,
        and ``path`` is the result of `get_absolute_path`

        This is an instance method called during request processing,
        so it may raise `HTTPError` or use methods like
        `RequestHandler.redirect` (return None after redirecting to
        halt further processing).  This is where 404 errors for missing files
        are generated.

        This method may modify the path before returning it, but note that
        any such modifications will not be understood by `make_static_url`.

        In instance methods, this method's result is available as
        ``self.absolute_path``.

        .. versionadded:: 3.1
        """
        root = os.path.abspath(root)
        # os.path.abspath strips a trailing /
        # it needs to be temporarily added back for requests to root/
        if not (absolute_path + os.path.sep).startswith(root):
            raise HTTPError(403, "%s is not in root static directory",
                            self.path)
        if (os.path.isdir(absolute_path) and
                self.default_filename is not None):
            # need to look at the request.path here for when path is empty
            # but there is some prefix to the path that was already
            # trimmed by the routing
            if not self.request.path.endswith("/"):
                self.redirect(self.request.path + "/", permanent=True)
                return
            absolute_path = os.path.join(absolute_path, self.default_filename)
        if not os.path.exists(absolute_path):
            raise HTTPError(404)
        if not os.path.isfile(absolute_path):
            raise HTTPError(403, "%s is not a file", self.path)
        return absolute_path

    @classmethod
    def get_content(cls, abspath, start=None, end=None):
        """Retrieve the content of the requested resource which is located
        at the given absolute path.

        This class method may be overridden by subclasses.  Note that its
        signature is different from other overridable class methods
        (no ``settings`` argument); this is deliberate to ensure that
        ``abspath`` is able to stand on its own as a cache key.

        This method should either return a byte string or an iterator
        of byte strings.  The latter is preferred for large files
        as it helps reduce memory fragmentation.

        .. versionadded:: 3.1
        """
        with open(abspath, "rb") as file:
            if start is not None:
                file.seek(start)
            if end is not None:
                remaining = end - (start or 0)
            else:
                remaining = None
            while True:
                chunk_size = 64 * 1024
                if remaining is not None and remaining < chunk_size:
                    chunk_size = remaining
                chunk = file.read(chunk_size)
                if chunk:
                    if remaining is not None:
                        remaining -= len(chunk)
                    yield chunk
                else:
                    if remaining is not None:
                        assert remaining == 0
                    return

    @classmethod
    def get_content_version(cls, abspath):
        """Returns a version string for the resource at the given path.

        This class method may be overridden by subclasses.  The
        default implementation is a hash of the file's contents.

        .. versionadded:: 3.1
        """
        data = cls.get_content(abspath)
        hasher = hashlib.md5()
        if isinstance(data, bytes_type):
            hasher.update(data)
        else:
            for chunk in data:
                hasher.update(chunk)
        return hasher.hexdigest()

    def _stat(self):
        if not hasattr(self, '_stat_result'):
            self._stat_result = os.stat(self.absolute_path)
        return self._stat_result

    def get_content_size(self):
        """Retrieve the total size of the resource at the given path.

        This method may be overridden by subclasses. It will only
        be called if a partial result is requested from `get_content`

        .. versionadded:: 3.1
        """
        stat_result = self._stat()
        return stat_result[stat.ST_SIZE]

    def get_modified_time(self):
        """Returns the time that ``self.absolute_path`` was last modified.

        May be overridden in subclasses.  Should return a `~datetime.datetime`
        object or None.

        .. versionadded:: 3.1
        """
        stat_result = self._stat()
        modified = datetime.datetime.utcfromtimestamp(stat_result[stat.ST_MTIME])
        return modified

    def get_content_type(self):
        """Returns the ``Content-Type`` header to be used for this request.

        .. versionadded:: 3.1
        """
        mime_type, encoding = mimetypes.guess_type(self.absolute_path)
        return mime_type

    def set_extra_headers(self, path):
        """For subclass to add extra headers to the response"""
        pass

    def get_cache_time(self, path, modified, mime_type):
        """Override to customize cache control behavior.

        Return a positive number of seconds to make the result
        cacheable for that amount of time or 0 to mark resource as
        cacheable for an unspecified amount of time (subject to
        browser heuristics).

        By default returns cache expiry of 10 years for resources requested
        with ``v`` argument.
        """
        return self.CACHE_MAX_AGE if "v" in self.request.arguments else 0

    @classmethod
    def make_static_url(cls, settings, path, include_version=True):
        """Constructs a versioned url for the given path.

        This method may be overridden in subclasses (but note that it
        is a class method rather than an instance method).  Subclasses
        are only required to implement the signature
        ``make_static_url(cls, settings, path)``; other keyword
        arguments may be passed through `~RequestHandler.static_url`
        but are not standard.

        ``settings`` is the `Application.settings` dictionary.  ``path``
        is the static path being requested.  The url returned should be
        relative to the current host.

        ``include_version`` determines whether the generated URL should
        include the query string containing the version hash of the
        file corresponding to the given ``path``.

        """
        url = settings.get('static_url_prefix', '/static/') + path
        if not include_version:
            return url

        version_hash = cls.get_version(settings, path)
        if not version_hash:
            return url

        return '%s?v=%s' % (url, version_hash)

    def parse_url_path(self, url_path):
        """Converts a static URL path into a filesystem path.

        ``url_path`` is the path component of the URL with
        ``static_url_prefix`` removed.  The return value should be
        filesystem path relative to ``static_path``.

        This is the inverse of `make_static_url`.
        """
        if os.path.sep != "/":
            url_path = url_path.replace("/", os.path.sep)
        return url_path

    @classmethod
    def get_version(cls, settings, path):
        """Generate the version string to be used in static URLs.

        ``settings`` is the `Application.settings` dictionary and ``path``
        is the relative location of the requested asset on the filesystem.
        The returned value should be a string, or ``None`` if no version
        could be determined.

        .. versionchanged:: 3.1
           This method was previously recommended for subclasses to override;
           `get_content_version` is now preferred as it allows the base
           class to handle caching of the result.
        """
        abs_path = cls.get_absolute_path(settings['static_path'], path)
        return cls._get_cached_version(abs_path)

    @classmethod
    def _get_cached_version(cls, abs_path):
        with cls._lock:
            hashes = cls._static_hashes
            if abs_path not in hashes:
                try:
                    hashes[abs_path] = cls.get_content_version(abs_path)
                except Exception:
                    gen_log.error("Could not open static file %r", abs_path)
                    hashes[abs_path] = None
            hsh = hashes.get(abs_path)
            if hsh:
                return hsh
        return None


class FallbackHandler(RequestHandler):
    """A `RequestHandler` that wraps another HTTP server callback.

    The fallback is a callable object that accepts an
    `~.httpserver.HTTPRequest`, such as an `Application` or
    `tornado.wsgi.WSGIContainer`.  This is most useful to use both
    Tornado ``RequestHandlers`` and WSGI in the same server.  Typical
    usage::

        wsgi_app = tornado.wsgi.WSGIContainer(
            django.core.handlers.wsgi.WSGIHandler())
        application = tornado.web.Application([
            (r"/foo", FooHandler),
            (r".*", FallbackHandler, dict(fallback=wsgi_app),
        ])
    """
    def initialize(self, fallback):
        self.fallback = fallback

    def prepare(self):
        self.fallback(self.request)
        self._finished = True


class OutputTransform(object):
    """A transform modifies the result of an HTTP request (e.g., GZip encoding)

    A new transform instance is created for every request. See the
    ChunkedTransferEncoding example below if you want to implement a
    new Transform.
    """
    def __init__(self, request):
        pass

    def transform_first_chunk(self, status_code, headers, chunk, finishing):
        return status_code, headers, chunk

    def transform_chunk(self, chunk, finishing):
        return chunk


class GZipContentEncoding(OutputTransform):
    """Applies the gzip content encoding to the response.

    See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11
    """
    CONTENT_TYPES = set([
        "text/plain", "text/html", "text/css", "text/xml", "application/javascript",
        "application/x-javascript", "application/xml", "application/atom+xml",
        "text/javascript", "application/json", "application/xhtml+xml"])
    MIN_LENGTH = 5

    def __init__(self, request):
        self._gzipping = request.supports_http_1_1() and \
            "gzip" in request.headers.get("Accept-Encoding", "")

    def transform_first_chunk(self, status_code, headers, chunk, finishing):
        if 'Vary' in headers:
            headers['Vary'] += b', Accept-Encoding'
        else:
            headers['Vary'] = b'Accept-Encoding'
        if self._gzipping:
            ctype = _unicode(headers.get("Content-Type", "")).split(";")[0]
            self._gzipping = (ctype in self.CONTENT_TYPES) and \
                (not finishing or len(chunk) >= self.MIN_LENGTH) and \
                (finishing or "Content-Length" not in headers) and \
                ("Content-Encoding" not in headers)
        if self._gzipping:
            headers["Content-Encoding"] = "gzip"
            self._gzip_value = BytesIO()
            self._gzip_file = gzip.GzipFile(mode="w", fileobj=self._gzip_value)
            chunk = self.transform_chunk(chunk, finishing)
            if "Content-Length" in headers:
                headers["Content-Length"] = str(len(chunk))
        return status_code, headers, chunk

    def transform_chunk(self, chunk, finishing):
        if self._gzipping:
            self._gzip_file.write(chunk)
            if finishing:
                self._gzip_file.close()
            else:
                self._gzip_file.flush()
            chunk = self._gzip_value.getvalue()
            self._gzip_value.truncate(0)
            self._gzip_value.seek(0)
        return chunk


class ChunkedTransferEncoding(OutputTransform):
    """Applies the chunked transfer encoding to the response.

    See http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.6.1
    """
    def __init__(self, request):
        self._chunking = request.supports_http_1_1()

    def transform_first_chunk(self, status_code, headers, chunk, finishing):
        # 304 responses have no body (not even a zero-length body), and so
        # should not have either Content-Length or Transfer-Encoding headers.
        if self._chunking and status_code != 304:
            # No need to chunk the output if a Content-Length is specified
            if "Content-Length" in headers or "Transfer-Encoding" in headers:
                self._chunking = False
            else:
                headers["Transfer-Encoding"] = "chunked"
                chunk = self.transform_chunk(chunk, finishing)
        return status_code, headers, chunk

    def transform_chunk(self, block, finishing):
        if self._chunking:
            # Don't write out empty chunks because that means END-OF-STREAM
            # with chunked encoding
            if block:
                block = utf8("%x" % len(block)) + b"\r\n" + block + b"\r\n"
            if finishing:
                block += b"0\r\n\r\n"
        return block


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


class UIModule(object):
    """A re-usable, modular UI unit on a page.

    UI modules often execute additional queries, and they can include
    additional CSS and JavaScript that will be included in the output
    page, which is automatically inserted on page render.
    """
    def __init__(self, handler):
        self.handler = handler
        self.request = handler.request
        self.ui = handler.ui
        self.current_user = handler.current_user
        self.locale = handler.locale

    def render(self, *args, **kwargs):
        """Overridden in subclasses to return this module's output."""
        raise NotImplementedError()

    def embedded_javascript(self):
        """Returns a JavaScript string that will be embedded in the page."""
        return None

    def javascript_files(self):
        """Returns a list of JavaScript files required by this module."""
        return None

    def embedded_css(self):
        """Returns a CSS string that will be embedded in the page."""
        return None

    def css_files(self):
        """Returns a list of CSS files required by this module."""
        return None

    def html_head(self):
        """Returns a CSS string that will be put in the <head/> element"""
        return None

    def html_body(self):
        """Returns an HTML string that will be put in the <body/> element"""
        return None

    def render_string(self, path, **kwargs):
        """Renders a template and returns it as a string."""
        return self.handler.render_string(path, **kwargs)


class _linkify(UIModule):
    def render(self, text, **kwargs):
        return escape.linkify(text, **kwargs)


class _xsrf_form_html(UIModule):
    def render(self):
        return self.handler.xsrf_form_html()


class TemplateModule(UIModule):
    """UIModule that simply renders the given template.

    {% module Template("foo.html") %} is similar to {% include "foo.html" %},
    but the module version gets its own namespace (with kwargs passed to
    Template()) instead of inheriting the outer template's namespace.

    Templates rendered through this module also get access to UIModule's
    automatic javascript/css features.  Simply call set_resources
    inside the template and give it keyword arguments corresponding to
    the methods on UIModule: {{ set_resources(js_files=static_url("my.js")) }}
    Note that these resources are output once per template file, not once
    per instantiation of the template, so they must not depend on
    any arguments to the template.
    """
    def __init__(self, handler):
        super(TemplateModule, self).__init__(handler)
        # keep resources in both a list and a dict to preserve order
        self._resource_list = []
        self._resource_dict = {}

    def render(self, path, **kwargs):
        def set_resources(**kwargs):
            if path not in self._resource_dict:
                self._resource_list.append(kwargs)
                self._resource_dict[path] = kwargs
            else:
                if self._resource_dict[path] != kwargs:
                    raise ValueError("set_resources called with different "
                                     "resources for the same template")
            return ""
        return self.render_string(path, set_resources=set_resources,
                                  **kwargs)

    def _get_resources(self, key):
        return (r[key] for r in self._resource_list if key in r)

    def embedded_javascript(self):
        return "\n".join(self._get_resources("embedded_javascript"))

    def javascript_files(self):
        result = []
        for f in self._get_resources("javascript_files"):
            if isinstance(f, (unicode_type, bytes_type)):
                result.append(f)
            else:
                result.extend(f)
        return result

    def embedded_css(self):
        return "\n".join(self._get_resources("embedded_css"))

    def css_files(self):
        result = []
        for f in self._get_resources("css_files"):
            if isinstance(f, (unicode_type, bytes_type)):
                result.append(f)
            else:
                result.extend(f)
        return result

    def html_head(self):
        return "".join(self._get_resources("html_head"))

    def html_body(self):
        return "".join(self._get_resources("html_body"))


class _UIModuleNamespace(object):
    """Lazy namespace which creates UIModule proxies bound to a handler."""
    def __init__(self, handler, ui_modules):
        self.handler = handler
        self.ui_modules = ui_modules

    def __getitem__(self, key):
        return self.handler._ui_module(key, self.ui_modules[key])

    def __getattr__(self, key):
        try:
            return self[key]
        except KeyError as e:
            raise AttributeError(str(e))


class URLSpec(object):
    """Specifies mappings between URLs and handlers."""
    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()

    def __repr__(self):
        return '%s(%r, %s, kwargs=%r, name=%r)' % \
            (self.__class__.__name__, self.regex.pattern,
             self.handler_class, self.kwargs, self.name)

    def _find_groups(self):
        """Returns a tuple (reverse string, group count) for a url.

        For example: Given the url pattern /([0-9]{4})/([a-z-]+)/, this method
        would return ('/%s/%s/', 2).
        """
        pattern = self.regex.pattern
        if pattern.startswith('^'):
            pattern = pattern[1:]
        if pattern.endswith('$'):
            pattern = pattern[:-1]

        if self.regex.groups != pattern.count('('):
            # The pattern is too complicated for our simplistic matching,
            # so we can't support reversing it.
            return (None, None)

        pieces = []
        for fragment in pattern.split('('):
            if ')' in fragment:
                paren_loc = fragment.index(')')
                if paren_loc >= 0:
                    pieces.append('%s' + fragment[paren_loc + 1:])
            else:
                pieces.append(fragment)

        return (''.join(pieces), self.regex.groups)

    def reverse(self, *args):
        assert self._path is not None, \
            "Cannot reverse url regex " + self.regex.pattern
        assert len(args) == self._group_count, "required number of arguments "\
            "not found"
        if not len(args):
            return self._path
        converted_args = []
        for a in args:
            if not isinstance(a, (unicode_type, bytes_type)):
                a = str(a)
            converted_args.append(escape.url_escape(utf8(a), plus=False))
        return self._path % tuple(converted_args)

url = URLSpec


if hasattr(hmac, 'compare_digest'):  # python 3.3
    _time_independent_equals = hmac.compare_digest
else:
    def _time_independent_equals(a, b):
        if len(a) != len(b):
            return False
        result = 0
        if isinstance(a[0], int):  # python3 byte strings
            for x, y in zip(a, b):
                result |= x ^ y
        else:  # python2
            for x, y in zip(a, b):
                result |= ord(x) ^ ord(y)
        return result == 0


def create_signed_value(secret, name, value):
    timestamp = utf8(str(int(time.time())))
    value = base64.b64encode(utf8(value))
    signature = _create_signature(secret, name, value, timestamp)
    value = b"|".join([value, timestamp, signature])
    return value


def decode_signed_value(secret, name, value, max_age_days=31):
    if not value:
        return None
    parts = utf8(value).split(b"|")
    if len(parts) != 3:
        return None
    signature = _create_signature(secret, name, parts[0], parts[1])
    if not _time_independent_equals(parts[2], signature):
        gen_log.warning("Invalid cookie signature %r", value)
        return None
    timestamp = int(parts[1])
    if timestamp < time.time() - max_age_days * 86400:
        gen_log.warning("Expired cookie %r", value)
        return None
    if timestamp > time.time() + 31 * 86400:
        # _cookie_signature does not hash a delimiter between the
        # parts of the cookie, so an attacker could transfer trailing
        # digits from the payload to the timestamp without altering the
        # signature.  For backwards compatibility, sanity-check timestamp
        # here instead of modifying _cookie_signature.
        gen_log.warning("Cookie timestamp in future; possible tampering %r", value)
        return None
    if parts[1].startswith(b"0"):
        gen_log.warning("Tampered cookie %r", value)
        return None
    try:
        return base64.b64decode(parts[0])
    except Exception:
        return None


def _create_signature(secret, *parts):
    hash = hmac.new(utf8(secret), digestmod=hashlib.sha1)
    for part in parts:
        hash.update(utf8(part))
    return utf8(hash.hexdigest())

```
--- END FILE ---

Please first localize the bug based on the issue statement, and then generate *SEARCH/REPLACE* edits to fix the issue.

Every *SEARCH/REPLACE* edit must use this format:
1. The file path
2. The start of search block: <<<<<<< SEARCH
3. A contiguous chunk of lines to search for in the existing source code
4. The dividing line: =======
5. The lines to replace into the source code
6. The end of the replace block: >>>>>>> REPLACE

Here is an example:

```python
### mathweb/flask/app.py
<<<<<<< SEARCH
from flask import Flask
=======
import math
from flask import Flask
>>>>>>> REPLACE
```
</solution>

Please note that the *SEARCH/REPLACE* edit REQUIRES PROPER INDENTATION. If you would like to add the line '        print(x)', you must fully write that out, with all those spaces before the code!
Wrap each *SEARCH/REPLACE* edit in a code block as shown in the example above. If you have multiple *SEARCH/REPLACE* edits, use a separate code block for each one.
user