{
    "file_diffs": [
        {
            "old_file_content": "from __future__ import absolute_import, division, print_function, with_statement\n\nimport contextlib\nimport functools\nimport sys\nimport textwrap\nimport time\n\nfrom tornado.concurrent import return_future\nfrom tornado.escape import url_escape\nfrom tornado.httpclient import AsyncHTTPClient\nfrom tornado.log import app_log\nfrom tornado import stack_context\nfrom tornado.testing import AsyncHTTPTestCase, AsyncTestCase, ExpectLog, gen_test\nfrom tornado.test.util import unittest, skipOnTravis\nfrom tornado.web import Application, RequestHandler, asynchronous\n\nfrom tornado import gen\n\n\nskipBefore33 = unittest.skipIf(sys.version_info < (3, 3), 'PEP 380 not available')\n\n\nclass GenEngineTest(AsyncTestCase):\n    def setUp(self):\n        super(GenEngineTest, self).setUp()\n        self.named_contexts = []\n\n    def named_context(self, name):\n        @contextlib.contextmanager\n        def context():\n            self.named_contexts.append(name)\n            try:\n                yield\n            finally:\n                self.assertEqual(self.named_contexts.pop(), name)\n        return context\n\n    def run_gen(self, f):\n        f()\n        return self.wait()\n\n    def delay_callback(self, iterations, callback, arg):\n        \"\"\"Runs callback(arg) after a number of IOLoop iterations.\"\"\"\n        if iterations == 0:\n            callback(arg)\n        else:\n            self.io_loop.add_callback(functools.partial(\n                self.delay_callback, iterations - 1, callback, arg))\n\n    @return_future\n    def async_future(self, result, callback):\n        self.io_loop.add_callback(callback, result)\n\n    def test_no_yield(self):\n        @gen.engine\n        def f():\n            self.stop()\n        self.run_gen(f)\n\n    def test_inline_cb(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))()\n            res = yield gen.Wait(\"k1\")\n            self.assertTrue(res is None)\n            self.stop()\n        self.run_gen(f)\n\n    def test_ioloop_cb(self):\n        @gen.engine\n        def f():\n            self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n            yield gen.Wait(\"k1\")\n            self.stop()\n        self.run_gen(f)\n\n    def test_exception_phase1(self):\n        @gen.engine\n        def f():\n            1 / 0\n        self.assertRaises(ZeroDivisionError, self.run_gen, f)\n\n    def test_exception_phase2(self):\n        @gen.engine\n        def f():\n            self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n            yield gen.Wait(\"k1\")\n            1 / 0\n        self.assertRaises(ZeroDivisionError, self.run_gen, f)\n\n    def test_exception_in_task_phase1(self):\n        def fail_task(callback):\n            1 / 0\n\n        @gen.engine\n        def f():\n            try:\n                yield gen.Task(fail_task)\n                raise Exception(\"did not get expected exception\")\n            except ZeroDivisionError:\n                self.stop()\n        self.run_gen(f)\n\n    def test_exception_in_task_phase2(self):\n        # This is the case that requires the use of stack_context in gen.engine\n        def fail_task(callback):\n            self.io_loop.add_callback(lambda: 1 / 0)\n\n        @gen.engine\n        def f():\n            try:\n                yield gen.Task(fail_task)\n                raise Exception(\"did not get expected exception\")\n            except ZeroDivisionError:\n                self.stop()\n        self.run_gen(f)\n\n    def test_with_arg(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))(42)\n            res = yield gen.Wait(\"k1\")\n            self.assertEqual(42, res)\n            self.stop()\n        self.run_gen(f)\n\n    def test_key_reuse(self):\n        @gen.engine\n        def f():\n            yield gen.Callback(\"k1\")\n            yield gen.Callback(\"k1\")\n            self.stop()\n        self.assertRaises(gen.KeyReuseError, self.run_gen, f)\n\n    def test_key_mismatch(self):\n        @gen.engine\n        def f():\n            yield gen.Callback(\"k1\")\n            yield gen.Wait(\"k2\")\n            self.stop()\n        self.assertRaises(gen.UnknownKeyError, self.run_gen, f)\n\n    def test_leaked_callback(self):\n        @gen.engine\n        def f():\n            yield gen.Callback(\"k1\")\n            self.stop()\n        self.assertRaises(gen.LeakedCallbackError, self.run_gen, f)\n\n    def test_parallel_callback(self):\n        @gen.engine\n        def f():\n            for k in range(3):\n                self.io_loop.add_callback((yield gen.Callback(k)))\n            yield gen.Wait(1)\n            self.io_loop.add_callback((yield gen.Callback(3)))\n            yield gen.Wait(0)\n            yield gen.Wait(3)\n            yield gen.Wait(2)\n            self.stop()\n        self.run_gen(f)\n\n    def test_bogus_yield(self):\n        @gen.engine\n        def f():\n            yield 42\n        self.assertRaises(gen.BadYieldError, self.run_gen, f)\n\n    def test_reuse(self):\n        @gen.engine\n        def f():\n            self.io_loop.add_callback((yield gen.Callback(0)))\n            yield gen.Wait(0)\n            self.stop()\n        self.run_gen(f)\n        self.run_gen(f)\n\n    def test_task(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            self.stop()\n        self.run_gen(f)\n\n    def test_wait_all(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))(\"v1\")\n            (yield gen.Callback(\"k2\"))(\"v2\")\n            results = yield gen.WaitAll([\"k1\", \"k2\"])\n            self.assertEqual(results, [\"v1\", \"v2\"])\n            self.stop()\n        self.run_gen(f)\n\n    def test_exception_in_yield(self):\n        @gen.engine\n        def f():\n            try:\n                yield gen.Wait(\"k1\")\n                raise Exception(\"did not get expected exception\")\n            except gen.UnknownKeyError:\n                pass\n            self.stop()\n        self.run_gen(f)\n\n    def test_resume_after_exception_in_yield(self):\n        @gen.engine\n        def f():\n            try:\n                yield gen.Wait(\"k1\")\n                raise Exception(\"did not get expected exception\")\n            except gen.UnknownKeyError:\n                pass\n            (yield gen.Callback(\"k2\"))(\"v2\")\n            self.assertEqual((yield gen.Wait(\"k2\")), \"v2\")\n            self.stop()\n        self.run_gen(f)\n\n    def test_orphaned_callback(self):\n        @gen.engine\n        def f():\n            self.orphaned_callback = yield gen.Callback(1)\n        try:\n            self.run_gen(f)\n            raise Exception(\"did not get expected exception\")\n        except gen.LeakedCallbackError:\n            pass\n        self.orphaned_callback()\n\n    def test_multi(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))(\"v1\")\n            (yield gen.Callback(\"k2\"))(\"v2\")\n            results = yield [gen.Wait(\"k1\"), gen.Wait(\"k2\")]\n            self.assertEqual(results, [\"v1\", \"v2\"])\n            self.stop()\n        self.run_gen(f)\n\n    def test_multi_delayed(self):\n        @gen.engine\n        def f():\n            # callbacks run at different times\n            responses = yield [\n                gen.Task(self.delay_callback, 3, arg=\"v1\"),\n                gen.Task(self.delay_callback, 1, arg=\"v2\"),\n            ]\n            self.assertEqual(responses, [\"v1\", \"v2\"])\n            self.stop()\n        self.run_gen(f)\n\n    @skipOnTravis\n    @gen_test\n    def test_multi_performance(self):\n        # Yielding a list used to have quadratic performance; make\n        # sure a large list stays reasonable.  On my laptop a list of\n        # 2000 used to take 1.8s, now it takes 0.12.\n        start = time.time()\n        yield [gen.Task(self.io_loop.add_callback) for i in range(2000)]\n        end = time.time()\n        self.assertLess(end - start, 1.0)\n\n    @gen_test\n    def test_future(self):\n        result = yield self.async_future(1)\n        self.assertEqual(result, 1)\n\n    @gen_test\n    def test_multi_future(self):\n        results = yield [self.async_future(1), self.async_future(2)]\n        self.assertEqual(results, [1, 2])\n\n    def test_arguments(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"noargs\"))()\n            self.assertEqual((yield gen.Wait(\"noargs\")), None)\n            (yield gen.Callback(\"1arg\"))(42)\n            self.assertEqual((yield gen.Wait(\"1arg\")), 42)\n\n            (yield gen.Callback(\"kwargs\"))(value=42)\n            result = yield gen.Wait(\"kwargs\")\n            self.assertTrue(isinstance(result, gen.Arguments))\n            self.assertEqual(((), dict(value=42)), result)\n            self.assertEqual(dict(value=42), result.kwargs)\n\n            (yield gen.Callback(\"2args\"))(42, 43)\n            result = yield gen.Wait(\"2args\")\n            self.assertTrue(isinstance(result, gen.Arguments))\n            self.assertEqual(((42, 43), {}), result)\n            self.assertEqual((42, 43), result.args)\n\n            def task_func(callback):\n                callback(None, error=\"foo\")\n            result = yield gen.Task(task_func)\n            self.assertTrue(isinstance(result, gen.Arguments))\n            self.assertEqual(((None,), dict(error=\"foo\")), result)\n\n            self.stop()\n        self.run_gen(f)\n\n    def test_stack_context_leak(self):\n        # regression test: repeated invocations of a gen-based\n        # function should not result in accumulated stack_contexts\n        @gen.engine\n        def inner(callback):\n            yield gen.Task(self.io_loop.add_callback)\n            callback()\n\n        @gen.engine\n        def outer():\n            for i in range(10):\n                yield gen.Task(inner)\n            stack_increase = len(stack_context._state.contexts) - initial_stack_depth\n            self.assertTrue(stack_increase <= 2)\n            self.stop()\n        initial_stack_depth = len(stack_context._state.contexts)\n        self.run_gen(outer)\n\n    def test_stack_context_leak_exception(self):\n        # same as previous, but with a function that exits with an exception\n        @gen.engine\n        def inner(callback):\n            yield gen.Task(self.io_loop.add_callback)\n            1 / 0\n\n        @gen.engine\n        def outer():\n            for i in range(10):\n                try:\n                    yield gen.Task(inner)\n                except ZeroDivisionError:\n                    pass\n            stack_increase = len(stack_context._state.contexts) - initial_stack_depth\n            self.assertTrue(stack_increase <= 2)\n            self.stop()\n        initial_stack_depth = len(stack_context._state.contexts)\n        self.run_gen(outer)\n\n    def function_with_stack_context(self, callback):\n        # Technically this function should stack_context.wrap its callback\n        # upon entry.  However, it is very common for this step to be\n        # omitted.\n        def step2():\n            self.assertEqual(self.named_contexts, ['a'])\n            self.io_loop.add_callback(callback)\n\n        with stack_context.StackContext(self.named_context('a')):\n            self.io_loop.add_callback(step2)\n\n    @gen_test\n    def test_wait_transfer_stack_context(self):\n        # Wait should not pick up contexts from where callback was invoked,\n        # even if that function improperly fails to wrap its callback.\n        cb = yield gen.Callback('k1')\n        self.function_with_stack_context(cb)\n        self.assertEqual(self.named_contexts, [])\n        yield gen.Wait('k1')\n        self.assertEqual(self.named_contexts, [])\n\n    @gen_test\n    def test_task_transfer_stack_context(self):\n        yield gen.Task(self.function_with_stack_context)\n        self.assertEqual(self.named_contexts, [])\n\n    def test_raise_after_stop(self):\n        # This pattern will be used in the following tests so make sure\n        # the exception propagates as expected.\n        @gen.engine\n        def f():\n            self.stop()\n            1 / 0\n\n        with self.assertRaises(ZeroDivisionError):\n            self.run_gen(f)\n\n    def test_sync_raise_return(self):\n        # gen.Return is allowed in @gen.engine, but it may not be used\n        # to return a value.\n        @gen.engine\n        def f():\n            self.stop(42)\n            raise gen.Return()\n\n        result = self.run_gen(f)\n        self.assertEqual(result, 42)\n\n    def test_async_raise_return(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            self.stop(42)\n            raise gen.Return()\n\n        result = self.run_gen(f)\n        self.assertEqual(result, 42)\n\n    def test_sync_raise_return_value(self):\n        @gen.engine\n        def f():\n            raise gen.Return(42)\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_async_raise_return_value(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            raise gen.Return(42)\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_return_value(self):\n        # It is an error to apply @gen.engine to a function that returns\n        # a value.\n        @gen.engine\n        def f():\n            return 42\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n\nclass GenCoroutineTest(AsyncTestCase):\n    def setUp(self):\n        # Stray StopIteration exceptions can lead to tests exiting prematurely,\n        # so we need explicit checks here to make sure the tests run all\n        # the way through.\n        self.finished = False\n        super(GenCoroutineTest, self).setUp()\n\n    def tearDown(self):\n        super(GenCoroutineTest, self).tearDown()\n        assert self.finished\n\n    @gen_test\n    def test_sync_gen_return(self):\n        @gen.coroutine\n        def f():\n            raise gen.Return(42)\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_async_gen_return(self):\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            raise gen.Return(42)\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_sync_return(self):\n        @gen.coroutine\n        def f():\n            return 42\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @skipBefore33\n    @gen_test\n    def test_async_return(self):\n        # It is a compile-time error to return a value in a generator\n        # before Python 3.3, so we must test this with exec.\n        # Flatten the real global and local namespace into our fake globals:\n        # it's all global from the perspective of f().\n        global_namespace = dict(globals(), **locals())\n        local_namespace = {}\n        exec(textwrap.dedent(\"\"\"\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            return 42\n        \"\"\"), global_namespace, local_namespace)\n        result = yield local_namespace['f']()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @skipBefore33\n    @gen_test\n    def test_async_early_return(self):\n        # A yield statement exists but is not executed, which means\n        # this function \"returns\" via an exception.  This exception\n        # doesn't happen before the exception handling is set up.\n        global_namespace = dict(globals(), **locals())\n        local_namespace = {}\n        exec(textwrap.dedent(\"\"\"\n        @gen.coroutine\n        def f():\n            if True:\n                return 42\n            yield gen.Task(self.io_loop.add_callback)\n        \"\"\"), global_namespace, local_namespace)\n        result = yield local_namespace['f']()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_sync_return_no_value(self):\n        @gen.coroutine\n        def f():\n            return\n        result = yield f()\n        self.assertEqual(result, None)\n        self.finished = True\n\n    @gen_test\n    def test_async_return_no_value(self):\n        # Without a return value we don't need python 3.3.\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            return\n        result = yield f()\n        self.assertEqual(result, None)\n        self.finished = True\n\n    @gen_test\n    def test_sync_raise(self):\n        @gen.coroutine\n        def f():\n            1 / 0\n        # The exception is raised when the future is yielded\n        # (or equivalently when its result method is called),\n        # not when the function itself is called).\n        future = f()\n        with self.assertRaises(ZeroDivisionError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_async_raise(self):\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            1 / 0\n        future = f()\n        with self.assertRaises(ZeroDivisionError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_pass_callback(self):\n        @gen.coroutine\n        def f():\n            raise gen.Return(42)\n        result = yield gen.Task(f)\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_replace_yieldpoint_exception(self):\n        # Test exception handling: a coroutine can catch one exception\n        # raised by a yield point and raise a different one.\n        @gen.coroutine\n        def f1():\n            1 / 0\n\n        @gen.coroutine\n        def f2():\n            try:\n                yield f1()\n            except ZeroDivisionError:\n                raise KeyError()\n\n        future = f2()\n        with self.assertRaises(KeyError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_swallow_yieldpoint_exception(self):\n        # Test exception handling: a coroutine can catch an exception\n        # raised by a yield point and not raise a different one.\n        @gen.coroutine\n        def f1():\n            1 / 0\n\n        @gen.coroutine\n        def f2():\n            try:\n                yield f1()\n            except ZeroDivisionError:\n                raise gen.Return(42)\n\n        result = yield f2()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_replace_context_exception(self):\n        # Test exception handling: exceptions thrown into the stack context\n        # can be caught and replaced.\n        @gen.coroutine\n        def f2():\n            self.io_loop.add_callback(lambda: 1 / 0)\n            try:\n                yield gen.Task(self.io_loop.add_timeout,\n                               self.io_loop.time() + 10)\n            except ZeroDivisionError:\n                raise KeyError()\n\n        future = f2()\n        with self.assertRaises(KeyError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_swallow_context_exception(self):\n        # Test exception handling: exceptions thrown into the stack context\n        # can be caught and ignored.\n        @gen.coroutine\n        def f2():\n            self.io_loop.add_callback(lambda: 1 / 0)\n            try:\n                yield gen.Task(self.io_loop.add_timeout,\n                               self.io_loop.time() + 10)\n            except ZeroDivisionError:\n                raise gen.Return(42)\n\n        result = yield f2()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n\nclass GenSequenceHandler(RequestHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        self.io_loop = self.request.connection.stream.io_loop\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.write(\"1\")\n        self.io_loop.add_callback((yield gen.Callback(\"k2\")))\n        yield gen.Wait(\"k2\")\n        self.write(\"2\")\n        # reuse an old key\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.finish(\"3\")\n\n\nclass GenTaskHandler(RequestHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        io_loop = self.request.connection.stream.io_loop\n        client = AsyncHTTPClient(io_loop=io_loop)\n        response = yield gen.Task(client.fetch, self.get_argument('url'))\n        response.rethrow()\n        self.finish(b\"got response: \" + response.body)\n\n\nclass GenExceptionHandler(RequestHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        # This test depends on the order of the two decorators.\n        io_loop = self.request.connection.stream.io_loop\n        yield gen.Task(io_loop.add_callback)\n        raise Exception(\"oops\")\n\n\nclass GenYieldExceptionHandler(RequestHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        io_loop = self.request.connection.stream.io_loop\n        # Test the interaction of the two stack_contexts.\n\n        def fail_task(callback):\n            io_loop.add_callback(lambda: 1 / 0)\n        try:\n            yield gen.Task(fail_task)\n            raise Exception(\"did not get expected exception\")\n        except ZeroDivisionError:\n            self.finish('ok')\n\n\nclass GenWebTest(AsyncHTTPTestCase):\n    def get_app(self):\n        return Application([\n            ('/sequence', GenSequenceHandler),\n            ('/task', GenTaskHandler),\n            ('/exception', GenExceptionHandler),\n            ('/yield_exception', GenYieldExceptionHandler),\n        ])\n\n    def test_sequence_handler(self):\n        response = self.fetch('/sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_task_handler(self):\n        response = self.fetch('/task?url=%s' % url_escape(self.get_url('/sequence')))\n        self.assertEqual(response.body, b\"got response: 123\")\n\n    def test_exception_handler(self):\n        # Make sure we get an error and not a timeout\n        with ExpectLog(app_log, \"Uncaught exception GET /exception\"):\n            response = self.fetch('/exception')\n        self.assertEqual(500, response.code)\n\n    def test_yield_exception_handler(self):\n        response = self.fetch('/yield_exception')\n        self.assertEqual(response.body, b'ok')\n",
            "new_file_content": "from __future__ import absolute_import, division, print_function, with_statement\n\nimport contextlib\nimport functools\nimport sys\nimport textwrap\nimport time\n\nfrom tornado.concurrent import return_future\nfrom tornado.escape import url_escape\nfrom tornado.httpclient import AsyncHTTPClient\nfrom tornado.log import app_log\nfrom tornado import stack_context\nfrom tornado.testing import AsyncHTTPTestCase, AsyncTestCase, ExpectLog, gen_test\nfrom tornado.test.util import unittest, skipOnTravis\nfrom tornado.web import Application, RequestHandler, asynchronous\n\nfrom tornado import gen\n\n\nskipBefore33 = unittest.skipIf(sys.version_info < (3, 3), 'PEP 380 not available')\n\n\nclass GenEngineTest(AsyncTestCase):\n    def setUp(self):\n        super(GenEngineTest, self).setUp()\n        self.named_contexts = []\n\n    def named_context(self, name):\n        @contextlib.contextmanager\n        def context():\n            self.named_contexts.append(name)\n            try:\n                yield\n            finally:\n                self.assertEqual(self.named_contexts.pop(), name)\n        return context\n\n    def run_gen(self, f):\n        f()\n        return self.wait()\n\n    def delay_callback(self, iterations, callback, arg):\n        \"\"\"Runs callback(arg) after a number of IOLoop iterations.\"\"\"\n        if iterations == 0:\n            callback(arg)\n        else:\n            self.io_loop.add_callback(functools.partial(\n                self.delay_callback, iterations - 1, callback, arg))\n\n    @return_future\n    def async_future(self, result, callback):\n        self.io_loop.add_callback(callback, result)\n\n    def test_no_yield(self):\n        @gen.engine\n        def f():\n            self.stop()\n        self.run_gen(f)\n\n    def test_inline_cb(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))()\n            res = yield gen.Wait(\"k1\")\n            self.assertTrue(res is None)\n            self.stop()\n        self.run_gen(f)\n\n    def test_ioloop_cb(self):\n        @gen.engine\n        def f():\n            self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n            yield gen.Wait(\"k1\")\n            self.stop()\n        self.run_gen(f)\n\n    def test_exception_phase1(self):\n        @gen.engine\n        def f():\n            1 / 0\n        self.assertRaises(ZeroDivisionError, self.run_gen, f)\n\n    def test_exception_phase2(self):\n        @gen.engine\n        def f():\n            self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n            yield gen.Wait(\"k1\")\n            1 / 0\n        self.assertRaises(ZeroDivisionError, self.run_gen, f)\n\n    def test_exception_in_task_phase1(self):\n        def fail_task(callback):\n            1 / 0\n\n        @gen.engine\n        def f():\n            try:\n                yield gen.Task(fail_task)\n                raise Exception(\"did not get expected exception\")\n            except ZeroDivisionError:\n                self.stop()\n        self.run_gen(f)\n\n    def test_exception_in_task_phase2(self):\n        # This is the case that requires the use of stack_context in gen.engine\n        def fail_task(callback):\n            self.io_loop.add_callback(lambda: 1 / 0)\n\n        @gen.engine\n        def f():\n            try:\n                yield gen.Task(fail_task)\n                raise Exception(\"did not get expected exception\")\n            except ZeroDivisionError:\n                self.stop()\n        self.run_gen(f)\n\n    def test_with_arg(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))(42)\n            res = yield gen.Wait(\"k1\")\n            self.assertEqual(42, res)\n            self.stop()\n        self.run_gen(f)\n\n    def test_key_reuse(self):\n        @gen.engine\n        def f():\n            yield gen.Callback(\"k1\")\n            yield gen.Callback(\"k1\")\n            self.stop()\n        self.assertRaises(gen.KeyReuseError, self.run_gen, f)\n\n    def test_key_mismatch(self):\n        @gen.engine\n        def f():\n            yield gen.Callback(\"k1\")\n            yield gen.Wait(\"k2\")\n            self.stop()\n        self.assertRaises(gen.UnknownKeyError, self.run_gen, f)\n\n    def test_leaked_callback(self):\n        @gen.engine\n        def f():\n            yield gen.Callback(\"k1\")\n            self.stop()\n        self.assertRaises(gen.LeakedCallbackError, self.run_gen, f)\n\n    def test_parallel_callback(self):\n        @gen.engine\n        def f():\n            for k in range(3):\n                self.io_loop.add_callback((yield gen.Callback(k)))\n            yield gen.Wait(1)\n            self.io_loop.add_callback((yield gen.Callback(3)))\n            yield gen.Wait(0)\n            yield gen.Wait(3)\n            yield gen.Wait(2)\n            self.stop()\n        self.run_gen(f)\n\n    def test_bogus_yield(self):\n        @gen.engine\n        def f():\n            yield 42\n        self.assertRaises(gen.BadYieldError, self.run_gen, f)\n\n    def test_reuse(self):\n        @gen.engine\n        def f():\n            self.io_loop.add_callback((yield gen.Callback(0)))\n            yield gen.Wait(0)\n            self.stop()\n        self.run_gen(f)\n        self.run_gen(f)\n\n    def test_task(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            self.stop()\n        self.run_gen(f)\n\n    def test_wait_all(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))(\"v1\")\n            (yield gen.Callback(\"k2\"))(\"v2\")\n            results = yield gen.WaitAll([\"k1\", \"k2\"])\n            self.assertEqual(results, [\"v1\", \"v2\"])\n            self.stop()\n        self.run_gen(f)\n\n    def test_exception_in_yield(self):\n        @gen.engine\n        def f():\n            try:\n                yield gen.Wait(\"k1\")\n                raise Exception(\"did not get expected exception\")\n            except gen.UnknownKeyError:\n                pass\n            self.stop()\n        self.run_gen(f)\n\n    def test_resume_after_exception_in_yield(self):\n        @gen.engine\n        def f():\n            try:\n                yield gen.Wait(\"k1\")\n                raise Exception(\"did not get expected exception\")\n            except gen.UnknownKeyError:\n                pass\n            (yield gen.Callback(\"k2\"))(\"v2\")\n            self.assertEqual((yield gen.Wait(\"k2\")), \"v2\")\n            self.stop()\n        self.run_gen(f)\n\n    def test_orphaned_callback(self):\n        @gen.engine\n        def f():\n            self.orphaned_callback = yield gen.Callback(1)\n        try:\n            self.run_gen(f)\n            raise Exception(\"did not get expected exception\")\n        except gen.LeakedCallbackError:\n            pass\n        self.orphaned_callback()\n\n    def test_multi(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))(\"v1\")\n            (yield gen.Callback(\"k2\"))(\"v2\")\n            results = yield [gen.Wait(\"k1\"), gen.Wait(\"k2\")]\n            self.assertEqual(results, [\"v1\", \"v2\"])\n            self.stop()\n        self.run_gen(f)\n\n    def test_multi_delayed(self):\n        @gen.engine\n        def f():\n            # callbacks run at different times\n            responses = yield [\n                gen.Task(self.delay_callback, 3, arg=\"v1\"),\n                gen.Task(self.delay_callback, 1, arg=\"v2\"),\n            ]\n            self.assertEqual(responses, [\"v1\", \"v2\"])\n            self.stop()\n        self.run_gen(f)\n\n    @skipOnTravis\n    @gen_test\n    def test_multi_performance(self):\n        # Yielding a list used to have quadratic performance; make\n        # sure a large list stays reasonable.  On my laptop a list of\n        # 2000 used to take 1.8s, now it takes 0.12.\n        start = time.time()\n        yield [gen.Task(self.io_loop.add_callback) for i in range(2000)]\n        end = time.time()\n        self.assertLess(end - start, 1.0)\n\n    @gen_test\n    def test_future(self):\n        result = yield self.async_future(1)\n        self.assertEqual(result, 1)\n\n    @gen_test\n    def test_multi_future(self):\n        results = yield [self.async_future(1), self.async_future(2)]\n        self.assertEqual(results, [1, 2])\n\n    def test_arguments(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"noargs\"))()\n            self.assertEqual((yield gen.Wait(\"noargs\")), None)\n            (yield gen.Callback(\"1arg\"))(42)\n            self.assertEqual((yield gen.Wait(\"1arg\")), 42)\n\n            (yield gen.Callback(\"kwargs\"))(value=42)\n            result = yield gen.Wait(\"kwargs\")\n            self.assertTrue(isinstance(result, gen.Arguments))\n            self.assertEqual(((), dict(value=42)), result)\n            self.assertEqual(dict(value=42), result.kwargs)\n\n            (yield gen.Callback(\"2args\"))(42, 43)\n            result = yield gen.Wait(\"2args\")\n            self.assertTrue(isinstance(result, gen.Arguments))\n            self.assertEqual(((42, 43), {}), result)\n            self.assertEqual((42, 43), result.args)\n\n            def task_func(callback):\n                callback(None, error=\"foo\")\n            result = yield gen.Task(task_func)\n            self.assertTrue(isinstance(result, gen.Arguments))\n            self.assertEqual(((None,), dict(error=\"foo\")), result)\n\n            self.stop()\n        self.run_gen(f)\n\n    def test_stack_context_leak(self):\n        # regression test: repeated invocations of a gen-based\n        # function should not result in accumulated stack_contexts\n        @gen.engine\n        def inner(callback):\n            yield gen.Task(self.io_loop.add_callback)\n            callback()\n\n        @gen.engine\n        def outer():\n            for i in range(10):\n                yield gen.Task(inner)\n            stack_increase = len(stack_context._state.contexts) - initial_stack_depth\n            self.assertTrue(stack_increase <= 2)\n            self.stop()\n        initial_stack_depth = len(stack_context._state.contexts)\n        self.run_gen(outer)\n\n    def test_stack_context_leak_exception(self):\n        # same as previous, but with a function that exits with an exception\n        @gen.engine\n        def inner(callback):\n            yield gen.Task(self.io_loop.add_callback)\n            1 / 0\n\n        @gen.engine\n        def outer():\n            for i in range(10):\n                try:\n                    yield gen.Task(inner)\n                except ZeroDivisionError:\n                    pass\n            stack_increase = len(stack_context._state.contexts) - initial_stack_depth\n            self.assertTrue(stack_increase <= 2)\n            self.stop()\n        initial_stack_depth = len(stack_context._state.contexts)\n        self.run_gen(outer)\n\n    def function_with_stack_context(self, callback):\n        # Technically this function should stack_context.wrap its callback\n        # upon entry.  However, it is very common for this step to be\n        # omitted.\n        def step2():\n            self.assertEqual(self.named_contexts, ['a'])\n            self.io_loop.add_callback(callback)\n\n        with stack_context.StackContext(self.named_context('a')):\n            self.io_loop.add_callback(step2)\n\n    @gen_test\n    def test_wait_transfer_stack_context(self):\n        # Wait should not pick up contexts from where callback was invoked,\n        # even if that function improperly fails to wrap its callback.\n        cb = yield gen.Callback('k1')\n        self.function_with_stack_context(cb)\n        self.assertEqual(self.named_contexts, [])\n        yield gen.Wait('k1')\n        self.assertEqual(self.named_contexts, [])\n\n    @gen_test\n    def test_task_transfer_stack_context(self):\n        yield gen.Task(self.function_with_stack_context)\n        self.assertEqual(self.named_contexts, [])\n\n    def test_raise_after_stop(self):\n        # This pattern will be used in the following tests so make sure\n        # the exception propagates as expected.\n        @gen.engine\n        def f():\n            self.stop()\n            1 / 0\n\n        with self.assertRaises(ZeroDivisionError):\n            self.run_gen(f)\n\n    def test_sync_raise_return(self):\n        # gen.Return is allowed in @gen.engine, but it may not be used\n        # to return a value.\n        @gen.engine\n        def f():\n            self.stop(42)\n            raise gen.Return()\n\n        result = self.run_gen(f)\n        self.assertEqual(result, 42)\n\n    def test_async_raise_return(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            self.stop(42)\n            raise gen.Return()\n\n        result = self.run_gen(f)\n        self.assertEqual(result, 42)\n\n    def test_sync_raise_return_value(self):\n        @gen.engine\n        def f():\n            raise gen.Return(42)\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_async_raise_return_value(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            raise gen.Return(42)\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_return_value(self):\n        # It is an error to apply @gen.engine to a function that returns\n        # a value.\n        @gen.engine\n        def f():\n            return 42\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n\nclass GenCoroutineTest(AsyncTestCase):\n    def setUp(self):\n        # Stray StopIteration exceptions can lead to tests exiting prematurely,\n        # so we need explicit checks here to make sure the tests run all\n        # the way through.\n        self.finished = False\n        super(GenCoroutineTest, self).setUp()\n\n    def tearDown(self):\n        super(GenCoroutineTest, self).tearDown()\n        assert self.finished\n\n    @gen_test\n    def test_sync_gen_return(self):\n        @gen.coroutine\n        def f():\n            raise gen.Return(42)\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_async_gen_return(self):\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            raise gen.Return(42)\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_sync_return(self):\n        @gen.coroutine\n        def f():\n            return 42\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @skipBefore33\n    @gen_test\n    def test_async_return(self):\n        # It is a compile-time error to return a value in a generator\n        # before Python 3.3, so we must test this with exec.\n        # Flatten the real global and local namespace into our fake globals:\n        # it's all global from the perspective of f().\n        global_namespace = dict(globals(), **locals())\n        local_namespace = {}\n        exec(textwrap.dedent(\"\"\"\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            return 42\n        \"\"\"), global_namespace, local_namespace)\n        result = yield local_namespace['f']()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @skipBefore33\n    @gen_test\n    def test_async_early_return(self):\n        # A yield statement exists but is not executed, which means\n        # this function \"returns\" via an exception.  This exception\n        # doesn't happen before the exception handling is set up.\n        global_namespace = dict(globals(), **locals())\n        local_namespace = {}\n        exec(textwrap.dedent(\"\"\"\n        @gen.coroutine\n        def f():\n            if True:\n                return 42\n            yield gen.Task(self.io_loop.add_callback)\n        \"\"\"), global_namespace, local_namespace)\n        result = yield local_namespace['f']()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_sync_return_no_value(self):\n        @gen.coroutine\n        def f():\n            return\n        result = yield f()\n        self.assertEqual(result, None)\n        self.finished = True\n\n    @gen_test\n    def test_async_return_no_value(self):\n        # Without a return value we don't need python 3.3.\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            return\n        result = yield f()\n        self.assertEqual(result, None)\n        self.finished = True\n\n    @gen_test\n    def test_sync_raise(self):\n        @gen.coroutine\n        def f():\n            1 / 0\n        # The exception is raised when the future is yielded\n        # (or equivalently when its result method is called),\n        # not when the function itself is called).\n        future = f()\n        with self.assertRaises(ZeroDivisionError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_async_raise(self):\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            1 / 0\n        future = f()\n        with self.assertRaises(ZeroDivisionError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_pass_callback(self):\n        @gen.coroutine\n        def f():\n            raise gen.Return(42)\n        result = yield gen.Task(f)\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_replace_yieldpoint_exception(self):\n        # Test exception handling: a coroutine can catch one exception\n        # raised by a yield point and raise a different one.\n        @gen.coroutine\n        def f1():\n            1 / 0\n\n        @gen.coroutine\n        def f2():\n            try:\n                yield f1()\n            except ZeroDivisionError:\n                raise KeyError()\n\n        future = f2()\n        with self.assertRaises(KeyError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_swallow_yieldpoint_exception(self):\n        # Test exception handling: a coroutine can catch an exception\n        # raised by a yield point and not raise a different one.\n        @gen.coroutine\n        def f1():\n            1 / 0\n\n        @gen.coroutine\n        def f2():\n            try:\n                yield f1()\n            except ZeroDivisionError:\n                raise gen.Return(42)\n\n        result = yield f2()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_replace_context_exception(self):\n        # Test exception handling: exceptions thrown into the stack context\n        # can be caught and replaced.\n        @gen.coroutine\n        def f2():\n            self.io_loop.add_callback(lambda: 1 / 0)\n            try:\n                yield gen.Task(self.io_loop.add_timeout,\n                               self.io_loop.time() + 10)\n            except ZeroDivisionError:\n                raise KeyError()\n\n        future = f2()\n        with self.assertRaises(KeyError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_swallow_context_exception(self):\n        # Test exception handling: exceptions thrown into the stack context\n        # can be caught and ignored.\n        @gen.coroutine\n        def f2():\n            self.io_loop.add_callback(lambda: 1 / 0)\n            try:\n                yield gen.Task(self.io_loop.add_timeout,\n                               self.io_loop.time() + 10)\n            except ZeroDivisionError:\n                raise gen.Return(42)\n\n        result = yield f2()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n\nclass GenSequenceHandler(RequestHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        self.io_loop = self.request.connection.stream.io_loop\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.write(\"1\")\n        self.io_loop.add_callback((yield gen.Callback(\"k2\")))\n        yield gen.Wait(\"k2\")\n        self.write(\"2\")\n        # reuse an old key\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.finish(\"3\")\n\n\nclass GenCoroutineSequenceHandler(RequestHandler):\n    @asynchronous\n    @gen.coroutine\n    def get(self):\n        self.io_loop = self.request.connection.stream.io_loop\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.write(\"1\")\n        self.io_loop.add_callback((yield gen.Callback(\"k2\")))\n        yield gen.Wait(\"k2\")\n        self.write(\"2\")\n        # reuse an old key\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.finish(\"3\")\n\n\nclass GenCoroutineUnfinishedSequenceHandler(RequestHandler):\n    @asynchronous\n    @gen.coroutine\n    def get(self):\n        self.io_loop = self.request.connection.stream.io_loop\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.write(\"1\")\n        self.io_loop.add_callback((yield gen.Callback(\"k2\")))\n        yield gen.Wait(\"k2\")\n        self.write(\"2\")\n        # reuse an old key\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        # just write, don't finish\n        self.write(\"3\")\n\n\nclass GenTaskHandler(RequestHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        io_loop = self.request.connection.stream.io_loop\n        client = AsyncHTTPClient(io_loop=io_loop)\n        response = yield gen.Task(client.fetch, self.get_argument('url'))\n        response.rethrow()\n        self.finish(b\"got response: \" + response.body)\n\n\nclass GenExceptionHandler(RequestHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        # This test depends on the order of the two decorators.\n        io_loop = self.request.connection.stream.io_loop\n        yield gen.Task(io_loop.add_callback)\n        raise Exception(\"oops\")\n\n\nclass GenCoroutineExceptionHandler(RequestHandler):\n    @asynchronous\n    @gen.coroutine\n    def get(self):\n        # This test depends on the order of the two decorators.\n        io_loop = self.request.connection.stream.io_loop\n        yield gen.Task(io_loop.add_callback)\n        raise Exception(\"oops\")\n\n\nclass GenYieldExceptionHandler(RequestHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        io_loop = self.request.connection.stream.io_loop\n        # Test the interaction of the two stack_contexts.\n\n        def fail_task(callback):\n            io_loop.add_callback(lambda: 1 / 0)\n        try:\n            yield gen.Task(fail_task)\n            raise Exception(\"did not get expected exception\")\n        except ZeroDivisionError:\n            self.finish('ok')\n\n\nclass GenWebTest(AsyncHTTPTestCase):\n    def get_app(self):\n        return Application([\n            ('/sequence', GenSequenceHandler),\n            ('/coroutine_sequence', GenCoroutineSequenceHandler),\n            ('/coroutine_unfinished_sequence',\n             GenCoroutineUnfinishedSequenceHandler),\n            ('/task', GenTaskHandler),\n            ('/exception', GenExceptionHandler),\n            ('/coroutine_exception', GenCoroutineExceptionHandler),\n            ('/yield_exception', GenYieldExceptionHandler),\n        ])\n\n    def test_sequence_handler(self):\n        response = self.fetch('/sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_coroutine_sequence_handler(self):\n        response = self.fetch('/coroutine_sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_coroutine_unfinished_sequence_handler(self):\n        response = self.fetch('/coroutine_unfinished_sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_task_handler(self):\n        response = self.fetch('/task?url=%s' % url_escape(self.get_url('/sequence')))\n        self.assertEqual(response.body, b\"got response: 123\")\n\n    def test_exception_handler(self):\n        # Make sure we get an error and not a timeout\n        with ExpectLog(app_log, \"Uncaught exception GET /exception\"):\n            response = self.fetch('/exception')\n        self.assertEqual(500, response.code)\n\n    def test_coroutine_exception_handler(self):\n        # Make sure we get an error and not a timeout\n        with ExpectLog(app_log, \"Uncaught exception GET /coroutine_exception\"):\n            response = self.fetch('/coroutine_exception')\n        self.assertEqual(500, response.code)\n\n    def test_yield_exception_handler(self):\n        response = self.fetch('/yield_exception')\n        self.assertEqual(response.body, b'ok')\n",
            "header": {
                "file": {
                    "path": "tornado/test/gen_test.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "5da8cfcf",
                "new_commit_hash": "a9db7bcb",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tornado/test/gen_test.py"
            },
            "plus_file": {
                "path": "b/tornado/test/gen_test.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 647,
                            "length": 6
                        },
                        "new_range": {
                            "start": 647,
                            "length": 41
                        },
                        "section": "class GenSequenceHandler(RequestHandler):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        self.finish(\"3\")",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "class GenCoroutineSequenceHandler(RequestHandler):",
                                "type": "added"
                            },
                            {
                                "content": "    @asynchronous",
                                "type": "added"
                            },
                            {
                                "content": "    @gen.coroutine",
                                "type": "added"
                            },
                            {
                                "content": "    def get(self):",
                                "type": "added"
                            },
                            {
                                "content": "        self.io_loop = self.request.connection.stream.io_loop",
                                "type": "added"
                            },
                            {
                                "content": "        self.io_loop.add_callback((yield gen.Callback(\"k1\")))",
                                "type": "added"
                            },
                            {
                                "content": "        yield gen.Wait(\"k1\")",
                                "type": "added"
                            },
                            {
                                "content": "        self.write(\"1\")",
                                "type": "added"
                            },
                            {
                                "content": "        self.io_loop.add_callback((yield gen.Callback(\"k2\")))",
                                "type": "added"
                            },
                            {
                                "content": "        yield gen.Wait(\"k2\")",
                                "type": "added"
                            },
                            {
                                "content": "        self.write(\"2\")",
                                "type": "added"
                            },
                            {
                                "content": "        # reuse an old key",
                                "type": "added"
                            },
                            {
                                "content": "        self.io_loop.add_callback((yield gen.Callback(\"k1\")))",
                                "type": "added"
                            },
                            {
                                "content": "        yield gen.Wait(\"k1\")",
                                "type": "added"
                            },
                            {
                                "content": "        self.finish(\"3\")",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "class GenCoroutineUnfinishedSequenceHandler(RequestHandler):",
                                "type": "added"
                            },
                            {
                                "content": "    @asynchronous",
                                "type": "added"
                            },
                            {
                                "content": "    @gen.coroutine",
                                "type": "added"
                            },
                            {
                                "content": "    def get(self):",
                                "type": "added"
                            },
                            {
                                "content": "        self.io_loop = self.request.connection.stream.io_loop",
                                "type": "added"
                            },
                            {
                                "content": "        self.io_loop.add_callback((yield gen.Callback(\"k1\")))",
                                "type": "added"
                            },
                            {
                                "content": "        yield gen.Wait(\"k1\")",
                                "type": "added"
                            },
                            {
                                "content": "        self.write(\"1\")",
                                "type": "added"
                            },
                            {
                                "content": "        self.io_loop.add_callback((yield gen.Callback(\"k2\")))",
                                "type": "added"
                            },
                            {
                                "content": "        yield gen.Wait(\"k2\")",
                                "type": "added"
                            },
                            {
                                "content": "        self.write(\"2\")",
                                "type": "added"
                            },
                            {
                                "content": "        # reuse an old key",
                                "type": "added"
                            },
                            {
                                "content": "        self.io_loop.add_callback((yield gen.Callback(\"k1\")))",
                                "type": "added"
                            },
                            {
                                "content": "        yield gen.Wait(\"k1\")",
                                "type": "added"
                            },
                            {
                                "content": "        # just write, don't finish",
                                "type": "added"
                            },
                            {
                                "content": "        self.write(\"3\")",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "class GenTaskHandler(RequestHandler):",
                                "type": "context"
                            },
                            {
                                "content": "    @asynchronous",
                                "type": "context"
                            },
                            {
                                "content": "    @gen.engine",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "tornado/test/gen_test.py",
                            "type": "class",
                            "name": "GenCoroutineSequenceHandler",
                            "content": "class GenCoroutineSequenceHandler(RequestHandler):\n    @asynchronous\n    @gen.coroutine\n    def get(self):\n        self.io_loop = self.request.connection.stream.io_loop\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.write(\"1\")\n        self.io_loop.add_callback((yield gen.Callback(\"k2\")))\n        yield gen.Wait(\"k2\")\n        self.write(\"2\")\n        # reuse an old key\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.finish(\"3\")",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 650,
                            "end_lineno": 664,
                            "parent": null
                        },
                        {
                            "file_name": "tornado/test/gen_test.py",
                            "type": "method",
                            "name": "GenCoroutineUnfinishedSequenceHandler.get",
                            "content": "class GenCoroutineUnfinishedSequenceHandler(RequestHandler):\n    @asynchronous\n    @gen.coroutine\n    def get(self):\n        self.io_loop = self.request.connection.stream.io_loop\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.write(\"1\")\n        self.io_loop.add_callback((yield gen.Callback(\"k2\")))\n        yield gen.Wait(\"k2\")\n        self.write(\"2\")\n        # reuse an old key\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        # just write, don't finish\n        self.write(\"3\")",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 670,
                            "end_lineno": 682,
                            "parent": {
                                "file_name": "tornado/test/gen_test.py",
                                "type": "class",
                                "name": "GenCoroutineUnfinishedSequenceHandler",
                                "content": "class GenCoroutineUnfinishedSequenceHandler(RequestHandler):\n    @asynchronous\n    @gen.coroutine\n    def get(self):\n        self.io_loop = self.request.connection.stream.io_loop\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.write(\"1\")\n        self.io_loop.add_callback((yield gen.Callback(\"k2\")))\n        yield gen.Wait(\"k2\")\n        self.write(\"2\")\n        # reuse an old key\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        # just write, don't finish\n        self.write(\"3\")",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 667,
                                "end_lineno": 682,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/test/gen_test.py",
                            "type": "class",
                            "name": "GenCoroutineUnfinishedSequenceHandler",
                            "content": "class GenCoroutineUnfinishedSequenceHandler(RequestHandler):\n    @asynchronous\n    @gen.coroutine\n    def get(self):\n        self.io_loop = self.request.connection.stream.io_loop\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.write(\"1\")\n        self.io_loop.add_callback((yield gen.Callback(\"k2\")))\n        yield gen.Wait(\"k2\")\n        self.write(\"2\")\n        # reuse an old key\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        # just write, don't finish\n        self.write(\"3\")",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 667,
                            "end_lineno": 682,
                            "parent": null
                        },
                        {
                            "file_name": "tornado/test/gen_test.py",
                            "type": "method",
                            "name": "GenCoroutineSequenceHandler.get",
                            "content": "class GenCoroutineSequenceHandler(RequestHandler):\n    @asynchronous\n    @gen.coroutine\n    def get(self):\n        self.io_loop = self.request.connection.stream.io_loop\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.write(\"1\")\n        self.io_loop.add_callback((yield gen.Callback(\"k2\")))\n        yield gen.Wait(\"k2\")\n        self.write(\"2\")\n        # reuse an old key\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.finish(\"3\")",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 653,
                            "end_lineno": 664,
                            "parent": {
                                "file_name": "tornado/test/gen_test.py",
                                "type": "class",
                                "name": "GenCoroutineSequenceHandler",
                                "content": "class GenCoroutineSequenceHandler(RequestHandler):\n    @asynchronous\n    @gen.coroutine\n    def get(self):\n        self.io_loop = self.request.connection.stream.io_loop\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.write(\"1\")\n        self.io_loop.add_callback((yield gen.Callback(\"k2\")))\n        yield gen.Wait(\"k2\")\n        self.write(\"2\")\n        # reuse an old key\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.finish(\"3\")",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 650,
                                "end_lineno": 664,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 668,
                            "length": 6
                        },
                        "new_range": {
                            "start": 703,
                            "length": 16
                        },
                        "section": "class GenExceptionHandler(RequestHandler):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        raise Exception(\"oops\")",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "class GenCoroutineExceptionHandler(RequestHandler):",
                                "type": "added"
                            },
                            {
                                "content": "    @asynchronous",
                                "type": "added"
                            },
                            {
                                "content": "    @gen.coroutine",
                                "type": "added"
                            },
                            {
                                "content": "    def get(self):",
                                "type": "added"
                            },
                            {
                                "content": "        # This test depends on the order of the two decorators.",
                                "type": "added"
                            },
                            {
                                "content": "        io_loop = self.request.connection.stream.io_loop",
                                "type": "added"
                            },
                            {
                                "content": "        yield gen.Task(io_loop.add_callback)",
                                "type": "added"
                            },
                            {
                                "content": "        raise Exception(\"oops\")",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "class GenYieldExceptionHandler(RequestHandler):",
                                "type": "context"
                            },
                            {
                                "content": "    @asynchronous",
                                "type": "context"
                            },
                            {
                                "content": "    @gen.engine",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "tornado/test/gen_test.py",
                            "type": "method",
                            "name": "GenCoroutineExceptionHandler.get",
                            "content": "class GenCoroutineExceptionHandler(RequestHandler):\n    @asynchronous\n    @gen.coroutine\n    def get(self):\n        # This test depends on the order of the two decorators.\n        io_loop = self.request.connection.stream.io_loop\n        yield gen.Task(io_loop.add_callback)\n        raise Exception(\"oops\")",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 709,
                            "end_lineno": 713,
                            "parent": {
                                "file_name": "tornado/test/gen_test.py",
                                "type": "class",
                                "name": "GenCoroutineExceptionHandler",
                                "content": "class GenCoroutineExceptionHandler(RequestHandler):\n    @asynchronous\n    @gen.coroutine\n    def get(self):\n        # This test depends on the order of the two decorators.\n        io_loop = self.request.connection.stream.io_loop\n        yield gen.Task(io_loop.add_callback)\n        raise Exception(\"oops\")",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 706,
                                "end_lineno": 713,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/test/gen_test.py",
                            "type": "class",
                            "name": "GenCoroutineExceptionHandler",
                            "content": "class GenCoroutineExceptionHandler(RequestHandler):\n    @asynchronous\n    @gen.coroutine\n    def get(self):\n        # This test depends on the order of the two decorators.\n        io_loop = self.request.connection.stream.io_loop\n        yield gen.Task(io_loop.add_callback)\n        raise Exception(\"oops\")",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 706,
                            "end_lineno": 713,
                            "parent": null
                        }
                    ],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 688,
                            "length": 8
                        },
                        "new_range": {
                            "start": 733,
                            "length": 12
                        },
                        "section": "class GenWebTest(AsyncHTTPTestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "    def get_app(self):",
                                "type": "context"
                            },
                            {
                                "content": "        return Application([",
                                "type": "context"
                            },
                            {
                                "content": "            ('/sequence', GenSequenceHandler),",
                                "type": "context"
                            },
                            {
                                "content": "            ('/coroutine_sequence', GenCoroutineSequenceHandler),",
                                "type": "added"
                            },
                            {
                                "content": "            ('/coroutine_unfinished_sequence',",
                                "type": "added"
                            },
                            {
                                "content": "             GenCoroutineUnfinishedSequenceHandler),",
                                "type": "added"
                            },
                            {
                                "content": "            ('/task', GenTaskHandler),",
                                "type": "context"
                            },
                            {
                                "content": "            ('/exception', GenExceptionHandler),",
                                "type": "context"
                            },
                            {
                                "content": "            ('/coroutine_exception', GenCoroutineExceptionHandler),",
                                "type": "added"
                            },
                            {
                                "content": "            ('/yield_exception', GenYieldExceptionHandler),",
                                "type": "context"
                            },
                            {
                                "content": "        ])",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/test/gen_test.py",
                            "type": "class",
                            "name": "GenWebTest",
                            "content": "class GenWebTest(AsyncHTTPTestCase):\n    def get_app(self):\n        return Application([\n            ('/sequence', GenSequenceHandler),\n            ('/coroutine_sequence', GenCoroutineSequenceHandler),\n            ('/coroutine_unfinished_sequence',\n             GenCoroutineUnfinishedSequenceHandler),\n            ('/task', GenTaskHandler),\n            ('/exception', GenExceptionHandler),\n            ('/coroutine_exception', GenCoroutineExceptionHandler),\n            ('/yield_exception', GenYieldExceptionHandler),\n        ])\n\n    def test_sequence_handler(self):\n        response = self.fetch('/sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_coroutine_sequence_handler(self):\n        response = self.fetch('/coroutine_sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_coroutine_unfinished_sequence_handler(self):\n        response = self.fetch('/coroutine_unfinished_sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_task_handler(self):\n        response = self.fetch('/task?url=%s' % url_escape(self.get_url('/sequence')))\n        self.assertEqual(response.body, b\"got response: 123\")\n\n    def test_exception_handler(self):\n        # Make sure we get an error and not a timeout\n        with ExpectLog(app_log, \"Uncaught exception GET /exception\"):\n            response = self.fetch('/exception')\n        self.assertEqual(500, response.code)\n\n    def test_coroutine_exception_handler(self):\n        # Make sure we get an error and not a timeout\n        with ExpectLog(app_log, \"Uncaught exception GET /coroutine_exception\"):\n            response = self.fetch('/coroutine_exception')\n        self.assertEqual(500, response.code)\n\n    def test_yield_exception_handler(self):\n        response = self.fetch('/yield_exception')\n        self.assertEqual(response.body, b'ok')",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 732,
                            "end_lineno": 775,
                            "parent": null
                        },
                        {
                            "file_name": "tornado/test/gen_test.py",
                            "type": "method",
                            "name": "GenWebTest.get_app",
                            "content": "class GenWebTest(AsyncHTTPTestCase):\n    def get_app(self):\n        return Application([\n            ('/sequence', GenSequenceHandler),\n            ('/coroutine_sequence', GenCoroutineSequenceHandler),\n            ('/coroutine_unfinished_sequence',\n             GenCoroutineUnfinishedSequenceHandler),\n            ('/task', GenTaskHandler),\n            ('/exception', GenExceptionHandler),\n            ('/coroutine_exception', GenCoroutineExceptionHandler),\n            ('/yield_exception', GenYieldExceptionHandler),\n        ])\n\n    def test_sequence_handler(self):\n        response = self.fetch('/sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_coroutine_sequence_handler(self):\n        response = self.fetch('/coroutine_sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_coroutine_unfinished_sequence_handler(self):\n        response = self.fetch('/coroutine_unfinished_sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_task_handler(self):\n        response = self.fetch('/task?url=%s' % url_escape(self.get_url('/sequence')))\n        self.assertEqual(response.body, b\"got response: 123\")\n\n    def test_exception_handler(self):\n        # Make sure we get an error and not a timeout\n        with ExpectLog(app_log, \"Uncaught exception GET /exception\"):\n            response = self.fetch('/exception')\n        self.assertEqual(500, response.code)\n\n    def test_coroutine_exception_handler(self):\n        # Make sure we get an error and not a timeout\n        with ExpectLog(app_log, \"Uncaught exception GET /coroutine_exception\"):\n            response = self.fetch('/coroutine_exception')\n        self.assertEqual(500, response.code)\n\n    def test_yield_exception_handler(self):\n        response = self.fetch('/yield_exception')\n        self.assertEqual(response.body, b'ok')",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 733,
                            "end_lineno": 743,
                            "parent": {
                                "file_name": "tornado/test/gen_test.py",
                                "type": "class",
                                "name": "GenWebTest",
                                "content": "class GenWebTest(AsyncHTTPTestCase):\n    def get_app(self):\n        return Application([\n            ('/sequence', GenSequenceHandler),\n            ('/coroutine_sequence', GenCoroutineSequenceHandler),\n            ('/coroutine_unfinished_sequence',\n             GenCoroutineUnfinishedSequenceHandler),\n            ('/task', GenTaskHandler),\n            ('/exception', GenExceptionHandler),\n            ('/coroutine_exception', GenCoroutineExceptionHandler),\n            ('/yield_exception', GenYieldExceptionHandler),\n        ])\n\n    def test_sequence_handler(self):\n        response = self.fetch('/sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_coroutine_sequence_handler(self):\n        response = self.fetch('/coroutine_sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_coroutine_unfinished_sequence_handler(self):\n        response = self.fetch('/coroutine_unfinished_sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_task_handler(self):\n        response = self.fetch('/task?url=%s' % url_escape(self.get_url('/sequence')))\n        self.assertEqual(response.body, b\"got response: 123\")\n\n    def test_exception_handler(self):\n        # Make sure we get an error and not a timeout\n        with ExpectLog(app_log, \"Uncaught exception GET /exception\"):\n            response = self.fetch('/exception')\n        self.assertEqual(500, response.code)\n\n    def test_coroutine_exception_handler(self):\n        # Make sure we get an error and not a timeout\n        with ExpectLog(app_log, \"Uncaught exception GET /coroutine_exception\"):\n            response = self.fetch('/coroutine_exception')\n        self.assertEqual(500, response.code)\n\n    def test_yield_exception_handler(self):\n        response = self.fetch('/yield_exception')\n        self.assertEqual(response.body, b'ok')",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 732,
                                "end_lineno": 775,
                                "parent": null
                            }
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 697,
                            "length": 6
                        },
                        "new_range": {
                            "start": 746,
                            "length": 14
                        },
                        "section": "class GenWebTest(AsyncHTTPTestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        response = self.fetch('/sequence')",
                                "type": "context"
                            },
                            {
                                "content": "        self.assertEqual(response.body, b\"123\")",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def test_coroutine_sequence_handler(self):",
                                "type": "added"
                            },
                            {
                                "content": "        response = self.fetch('/coroutine_sequence')",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(response.body, b\"123\")",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def test_coroutine_unfinished_sequence_handler(self):",
                                "type": "added"
                            },
                            {
                                "content": "        response = self.fetch('/coroutine_unfinished_sequence')",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(response.body, b\"123\")",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def test_task_handler(self):",
                                "type": "context"
                            },
                            {
                                "content": "        response = self.fetch('/task?url=%s' % url_escape(self.get_url('/sequence')))",
                                "type": "context"
                            },
                            {
                                "content": "        self.assertEqual(response.body, b\"got response: 123\")",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/test/gen_test.py",
                            "type": "class",
                            "name": "GenWebTest",
                            "content": "class GenWebTest(AsyncHTTPTestCase):\n    def get_app(self):\n        return Application([\n            ('/sequence', GenSequenceHandler),\n            ('/coroutine_sequence', GenCoroutineSequenceHandler),\n            ('/coroutine_unfinished_sequence',\n             GenCoroutineUnfinishedSequenceHandler),\n            ('/task', GenTaskHandler),\n            ('/exception', GenExceptionHandler),\n            ('/coroutine_exception', GenCoroutineExceptionHandler),\n            ('/yield_exception', GenYieldExceptionHandler),\n        ])\n\n    def test_sequence_handler(self):\n        response = self.fetch('/sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_coroutine_sequence_handler(self):\n        response = self.fetch('/coroutine_sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_coroutine_unfinished_sequence_handler(self):\n        response = self.fetch('/coroutine_unfinished_sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_task_handler(self):\n        response = self.fetch('/task?url=%s' % url_escape(self.get_url('/sequence')))\n        self.assertEqual(response.body, b\"got response: 123\")\n\n    def test_exception_handler(self):\n        # Make sure we get an error and not a timeout\n        with ExpectLog(app_log, \"Uncaught exception GET /exception\"):\n            response = self.fetch('/exception')\n        self.assertEqual(500, response.code)\n\n    def test_coroutine_exception_handler(self):\n        # Make sure we get an error and not a timeout\n        with ExpectLog(app_log, \"Uncaught exception GET /coroutine_exception\"):\n            response = self.fetch('/coroutine_exception')\n        self.assertEqual(500, response.code)\n\n    def test_yield_exception_handler(self):\n        response = self.fetch('/yield_exception')\n        self.assertEqual(response.body, b'ok')",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 732,
                            "end_lineno": 775,
                            "parent": null
                        }
                    ],
                    "added_entities": [
                        {
                            "file_name": "tornado/test/gen_test.py",
                            "type": "method",
                            "name": "GenWebTest.test_coroutine_sequence_handler",
                            "content": "class GenWebTest(AsyncHTTPTestCase):\n    def get_app(self):\n        return Application([\n            ('/sequence', GenSequenceHandler),\n            ('/coroutine_sequence', GenCoroutineSequenceHandler),\n            ('/coroutine_unfinished_sequence',\n             GenCoroutineUnfinishedSequenceHandler),\n            ('/task', GenTaskHandler),\n            ('/exception', GenExceptionHandler),\n            ('/coroutine_exception', GenCoroutineExceptionHandler),\n            ('/yield_exception', GenYieldExceptionHandler),\n        ])\n\n    def test_sequence_handler(self):\n        response = self.fetch('/sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_coroutine_sequence_handler(self):\n        response = self.fetch('/coroutine_sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_coroutine_unfinished_sequence_handler(self):\n        response = self.fetch('/coroutine_unfinished_sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_task_handler(self):\n        response = self.fetch('/task?url=%s' % url_escape(self.get_url('/sequence')))\n        self.assertEqual(response.body, b\"got response: 123\")\n\n    def test_exception_handler(self):\n        # Make sure we get an error and not a timeout\n        with ExpectLog(app_log, \"Uncaught exception GET /exception\"):\n            response = self.fetch('/exception')\n        self.assertEqual(500, response.code)\n\n    def test_coroutine_exception_handler(self):\n        # Make sure we get an error and not a timeout\n        with ExpectLog(app_log, \"Uncaught exception GET /coroutine_exception\"):\n            response = self.fetch('/coroutine_exception')\n        self.assertEqual(500, response.code)\n\n    def test_yield_exception_handler(self):\n        response = self.fetch('/yield_exception')\n        self.assertEqual(response.body, b'ok')",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 749,
                            "end_lineno": 751,
                            "parent": {
                                "file_name": "tornado/test/gen_test.py",
                                "type": "class",
                                "name": "GenWebTest",
                                "content": "class GenWebTest(AsyncHTTPTestCase):\n    def get_app(self):\n        return Application([\n            ('/sequence', GenSequenceHandler),\n            ('/coroutine_sequence', GenCoroutineSequenceHandler),\n            ('/coroutine_unfinished_sequence',\n             GenCoroutineUnfinishedSequenceHandler),\n            ('/task', GenTaskHandler),\n            ('/exception', GenExceptionHandler),\n            ('/coroutine_exception', GenCoroutineExceptionHandler),\n            ('/yield_exception', GenYieldExceptionHandler),\n        ])\n\n    def test_sequence_handler(self):\n        response = self.fetch('/sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_coroutine_sequence_handler(self):\n        response = self.fetch('/coroutine_sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_coroutine_unfinished_sequence_handler(self):\n        response = self.fetch('/coroutine_unfinished_sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_task_handler(self):\n        response = self.fetch('/task?url=%s' % url_escape(self.get_url('/sequence')))\n        self.assertEqual(response.body, b\"got response: 123\")\n\n    def test_exception_handler(self):\n        # Make sure we get an error and not a timeout\n        with ExpectLog(app_log, \"Uncaught exception GET /exception\"):\n            response = self.fetch('/exception')\n        self.assertEqual(500, response.code)\n\n    def test_coroutine_exception_handler(self):\n        # Make sure we get an error and not a timeout\n        with ExpectLog(app_log, \"Uncaught exception GET /coroutine_exception\"):\n            response = self.fetch('/coroutine_exception')\n        self.assertEqual(500, response.code)\n\n    def test_yield_exception_handler(self):\n        response = self.fetch('/yield_exception')\n        self.assertEqual(response.body, b'ok')",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 732,
                                "end_lineno": 775,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/test/gen_test.py",
                            "type": "method",
                            "name": "GenWebTest.test_coroutine_unfinished_sequence_handler",
                            "content": "class GenWebTest(AsyncHTTPTestCase):\n    def get_app(self):\n        return Application([\n            ('/sequence', GenSequenceHandler),\n            ('/coroutine_sequence', GenCoroutineSequenceHandler),\n            ('/coroutine_unfinished_sequence',\n             GenCoroutineUnfinishedSequenceHandler),\n            ('/task', GenTaskHandler),\n            ('/exception', GenExceptionHandler),\n            ('/coroutine_exception', GenCoroutineExceptionHandler),\n            ('/yield_exception', GenYieldExceptionHandler),\n        ])\n\n    def test_sequence_handler(self):\n        response = self.fetch('/sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_coroutine_sequence_handler(self):\n        response = self.fetch('/coroutine_sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_coroutine_unfinished_sequence_handler(self):\n        response = self.fetch('/coroutine_unfinished_sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_task_handler(self):\n        response = self.fetch('/task?url=%s' % url_escape(self.get_url('/sequence')))\n        self.assertEqual(response.body, b\"got response: 123\")\n\n    def test_exception_handler(self):\n        # Make sure we get an error and not a timeout\n        with ExpectLog(app_log, \"Uncaught exception GET /exception\"):\n            response = self.fetch('/exception')\n        self.assertEqual(500, response.code)\n\n    def test_coroutine_exception_handler(self):\n        # Make sure we get an error and not a timeout\n        with ExpectLog(app_log, \"Uncaught exception GET /coroutine_exception\"):\n            response = self.fetch('/coroutine_exception')\n        self.assertEqual(500, response.code)\n\n    def test_yield_exception_handler(self):\n        response = self.fetch('/yield_exception')\n        self.assertEqual(response.body, b'ok')",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 753,
                            "end_lineno": 755,
                            "parent": {
                                "file_name": "tornado/test/gen_test.py",
                                "type": "class",
                                "name": "GenWebTest",
                                "content": "class GenWebTest(AsyncHTTPTestCase):\n    def get_app(self):\n        return Application([\n            ('/sequence', GenSequenceHandler),\n            ('/coroutine_sequence', GenCoroutineSequenceHandler),\n            ('/coroutine_unfinished_sequence',\n             GenCoroutineUnfinishedSequenceHandler),\n            ('/task', GenTaskHandler),\n            ('/exception', GenExceptionHandler),\n            ('/coroutine_exception', GenCoroutineExceptionHandler),\n            ('/yield_exception', GenYieldExceptionHandler),\n        ])\n\n    def test_sequence_handler(self):\n        response = self.fetch('/sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_coroutine_sequence_handler(self):\n        response = self.fetch('/coroutine_sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_coroutine_unfinished_sequence_handler(self):\n        response = self.fetch('/coroutine_unfinished_sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_task_handler(self):\n        response = self.fetch('/task?url=%s' % url_escape(self.get_url('/sequence')))\n        self.assertEqual(response.body, b\"got response: 123\")\n\n    def test_exception_handler(self):\n        # Make sure we get an error and not a timeout\n        with ExpectLog(app_log, \"Uncaught exception GET /exception\"):\n            response = self.fetch('/exception')\n        self.assertEqual(500, response.code)\n\n    def test_coroutine_exception_handler(self):\n        # Make sure we get an error and not a timeout\n        with ExpectLog(app_log, \"Uncaught exception GET /coroutine_exception\"):\n            response = self.fetch('/coroutine_exception')\n        self.assertEqual(500, response.code)\n\n    def test_yield_exception_handler(self):\n        response = self.fetch('/yield_exception')\n        self.assertEqual(response.body, b'ok')",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 732,
                                "end_lineno": 775,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 707,
                            "length": 6
                        },
                        "new_range": {
                            "start": 764,
                            "length": 12
                        },
                        "section": "class GenWebTest(AsyncHTTPTestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "            response = self.fetch('/exception')",
                                "type": "context"
                            },
                            {
                                "content": "        self.assertEqual(500, response.code)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def test_coroutine_exception_handler(self):",
                                "type": "added"
                            },
                            {
                                "content": "        # Make sure we get an error and not a timeout",
                                "type": "added"
                            },
                            {
                                "content": "        with ExpectLog(app_log, \"Uncaught exception GET /coroutine_exception\"):",
                                "type": "added"
                            },
                            {
                                "content": "            response = self.fetch('/coroutine_exception')",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(500, response.code)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def test_yield_exception_handler(self):",
                                "type": "context"
                            },
                            {
                                "content": "        response = self.fetch('/yield_exception')",
                                "type": "context"
                            },
                            {
                                "content": "        self.assertEqual(response.body, b'ok')",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/test/gen_test.py",
                            "type": "class",
                            "name": "GenWebTest",
                            "content": "class GenWebTest(AsyncHTTPTestCase):\n    def get_app(self):\n        return Application([\n            ('/sequence', GenSequenceHandler),\n            ('/coroutine_sequence', GenCoroutineSequenceHandler),\n            ('/coroutine_unfinished_sequence',\n             GenCoroutineUnfinishedSequenceHandler),\n            ('/task', GenTaskHandler),\n            ('/exception', GenExceptionHandler),\n            ('/coroutine_exception', GenCoroutineExceptionHandler),\n            ('/yield_exception', GenYieldExceptionHandler),\n        ])\n\n    def test_sequence_handler(self):\n        response = self.fetch('/sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_coroutine_sequence_handler(self):\n        response = self.fetch('/coroutine_sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_coroutine_unfinished_sequence_handler(self):\n        response = self.fetch('/coroutine_unfinished_sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_task_handler(self):\n        response = self.fetch('/task?url=%s' % url_escape(self.get_url('/sequence')))\n        self.assertEqual(response.body, b\"got response: 123\")\n\n    def test_exception_handler(self):\n        # Make sure we get an error and not a timeout\n        with ExpectLog(app_log, \"Uncaught exception GET /exception\"):\n            response = self.fetch('/exception')\n        self.assertEqual(500, response.code)\n\n    def test_coroutine_exception_handler(self):\n        # Make sure we get an error and not a timeout\n        with ExpectLog(app_log, \"Uncaught exception GET /coroutine_exception\"):\n            response = self.fetch('/coroutine_exception')\n        self.assertEqual(500, response.code)\n\n    def test_yield_exception_handler(self):\n        response = self.fetch('/yield_exception')\n        self.assertEqual(response.body, b'ok')",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 732,
                            "end_lineno": 775,
                            "parent": null
                        }
                    ],
                    "added_entities": [
                        {
                            "file_name": "tornado/test/gen_test.py",
                            "type": "method",
                            "name": "GenWebTest.test_coroutine_exception_handler",
                            "content": "class GenWebTest(AsyncHTTPTestCase):\n    def get_app(self):\n        return Application([\n            ('/sequence', GenSequenceHandler),\n            ('/coroutine_sequence', GenCoroutineSequenceHandler),\n            ('/coroutine_unfinished_sequence',\n             GenCoroutineUnfinishedSequenceHandler),\n            ('/task', GenTaskHandler),\n            ('/exception', GenExceptionHandler),\n            ('/coroutine_exception', GenCoroutineExceptionHandler),\n            ('/yield_exception', GenYieldExceptionHandler),\n        ])\n\n    def test_sequence_handler(self):\n        response = self.fetch('/sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_coroutine_sequence_handler(self):\n        response = self.fetch('/coroutine_sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_coroutine_unfinished_sequence_handler(self):\n        response = self.fetch('/coroutine_unfinished_sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_task_handler(self):\n        response = self.fetch('/task?url=%s' % url_escape(self.get_url('/sequence')))\n        self.assertEqual(response.body, b\"got response: 123\")\n\n    def test_exception_handler(self):\n        # Make sure we get an error and not a timeout\n        with ExpectLog(app_log, \"Uncaught exception GET /exception\"):\n            response = self.fetch('/exception')\n        self.assertEqual(500, response.code)\n\n    def test_coroutine_exception_handler(self):\n        # Make sure we get an error and not a timeout\n        with ExpectLog(app_log, \"Uncaught exception GET /coroutine_exception\"):\n            response = self.fetch('/coroutine_exception')\n        self.assertEqual(500, response.code)\n\n    def test_yield_exception_handler(self):\n        response = self.fetch('/yield_exception')\n        self.assertEqual(response.body, b'ok')",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 767,
                            "end_lineno": 771,
                            "parent": {
                                "file_name": "tornado/test/gen_test.py",
                                "type": "class",
                                "name": "GenWebTest",
                                "content": "class GenWebTest(AsyncHTTPTestCase):\n    def get_app(self):\n        return Application([\n            ('/sequence', GenSequenceHandler),\n            ('/coroutine_sequence', GenCoroutineSequenceHandler),\n            ('/coroutine_unfinished_sequence',\n             GenCoroutineUnfinishedSequenceHandler),\n            ('/task', GenTaskHandler),\n            ('/exception', GenExceptionHandler),\n            ('/coroutine_exception', GenCoroutineExceptionHandler),\n            ('/yield_exception', GenYieldExceptionHandler),\n        ])\n\n    def test_sequence_handler(self):\n        response = self.fetch('/sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_coroutine_sequence_handler(self):\n        response = self.fetch('/coroutine_sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_coroutine_unfinished_sequence_handler(self):\n        response = self.fetch('/coroutine_unfinished_sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_task_handler(self):\n        response = self.fetch('/task?url=%s' % url_escape(self.get_url('/sequence')))\n        self.assertEqual(response.body, b\"got response: 123\")\n\n    def test_exception_handler(self):\n        # Make sure we get an error and not a timeout\n        with ExpectLog(app_log, \"Uncaught exception GET /exception\"):\n            response = self.fetch('/exception')\n        self.assertEqual(500, response.code)\n\n    def test_coroutine_exception_handler(self):\n        # Make sure we get an error and not a timeout\n        with ExpectLog(app_log, \"Uncaught exception GET /coroutine_exception\"):\n            response = self.fetch('/coroutine_exception')\n        self.assertEqual(500, response.code)\n\n    def test_yield_exception_handler(self):\n        response = self.fetch('/yield_exception')\n        self.assertEqual(response.body, b'ok')",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 732,
                                "end_lineno": 775,
                                "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\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 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 `_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 `_modules` to avoid\n        # possible conflicts.\n        self.ui[\"_modules\"] = ObjectDict((n, self._ui_module(n, m)) for n, m in\n                                         application.ui_modules.items())\n        self.ui[\"modules\"] = self.ui[\"_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        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.gmtime()),\n        })\n        self.set_default_headers()\n        if not self.request.supports_http_1_1():\n            if self.request.headers.get(\"Connection\") == \"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    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 re.search(br\"[\\x00-\\x1f]\", 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 throw an HTTP 400 exception 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 HTTPError(400, \"Missing argument %s\" % 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        # Remove whitespace\n        url = re.sub(br\"[\\x00-\\x20]+\", \"\", utf8(url))\n        self.set_header(\"Location\", urlparse.urljoin(utf8(self.request.uri),\n                                                     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            raise Exception(\"WSGI applications do not support flush()\")\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                etag = self.compute_etag()\n                if etag is not None:\n                    self.set_header(\"Etag\", etag)\n                    inm = self.request.headers.get(\"If-None-Match\")\n                    if inm and inm.find(etag) != -1:\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\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    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):\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        We append ``?v=<signature>`` to the returned URL, which makes our\n        static file handler set an infinite expiration header on the\n        returned content. The signature is based on the content of the\n        file.\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        self.require_setting(\"static_path\", \"static_url\")\n        static_handler_class = self.settings.get(\n            \"static_handler_class\", StaticFileHandler)\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        return base + static_handler_class.make_static_url(self.settings, path)\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        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 _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.prepare()\n            if not self._finished:\n                getattr(self, self.request.method.lower())(\n                    *self.path_args, **self.path_kwargs)\n                if self._auto_finish and not self._finished:\n                    self.finish()\n        except Exception as e:\n            self._handle_request_exception(e)\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        if isinstance(e, HTTPError):\n            if e.log_message:\n                format = \"%d %s: \" + e.log_message\n                args = [e.status_code, self._request_summary()] + list(e.args)\n                gen_log.warning(format, *args)\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            app_log.error(\"Uncaught exception %s\\n%r\", self._request_summary(),\n                          self.request, exc_info=True)\n            self.send_error(500, exc_info=sys.exc_info())\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    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    \"\"\"\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            return method(self, *args, **kwargs)\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, type(())):\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                        # 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 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    To map a path to this handler for a static data directory ``/var/www``,\n    you would add a line to your application like::\n\n        application = web.Application([\n            (r\"/static/(.*)\", web.StaticFileHandler, {\"path\": \"/var/www\"}),\n        ])\n\n    The local root directory of the content should be passed as the ``path``\n    argument to the handler.\n\n    To support aggressive browser caching, if the argument ``v`` is given\n    with the path, we set an infinite HTTP expiration header. So, if you\n    want browsers to cache a file indefinitely, send them to, e.g.,\n    ``/static/images/myimage.png?v=xxx``. Override `get_cache_time` method for\n    more fine-grained cache control.\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 = os.path.abspath(path) + os.path.sep\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        path = self.parse_url_path(path)\n        abspath = os.path.abspath(os.path.join(self.root, path))\n        # os.path.abspath strips a trailing /\n        # it needs to be temporarily added back for requests to root/\n        if not (abspath + os.path.sep).startswith(self.root):\n            raise HTTPError(403, \"%s is not in root static directory\", path)\n        if os.path.isdir(abspath) and 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 + \"/\")\n                return\n            abspath = os.path.join(abspath, self.default_filename)\n        if not os.path.exists(abspath):\n            raise HTTPError(404)\n        if not os.path.isfile(abspath):\n            raise HTTPError(403, \"%s is not a file\", path)\n\n        stat_result = os.stat(abspath)\n        modified = datetime.datetime.fromtimestamp(stat_result[stat.ST_MTIME])\n\n        self.set_header(\"Last-Modified\", modified)\n\n        mime_type, encoding = mimetypes.guess_type(abspath)\n        if mime_type:\n            self.set_header(\"Content-Type\", mime_type)\n\n        cache_time = self.get_cache_time(path, modified, mime_type)\n\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(path)\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_since = datetime.datetime.fromtimestamp(time.mktime(date_tuple))\n            if if_since >= modified:\n                self.set_status(304)\n                return\n\n        with open(abspath, \"rb\") as file:\n            data = file.read()\n            if include_body:\n                self.write(data)\n            else:\n                assert self.request.method == \"HEAD\"\n                self.set_header(\"Content-Length\", len(data))\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):\n        \"\"\"Constructs a versioned url for the given path.\n\n        This method may be overridden in subclasses (but note that it is\n        a class method rather than an instance method).\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        static_url_prefix = settings.get('static_url_prefix', '/static/')\n        version_hash = cls.get_version(settings, path)\n        if version_hash:\n            return static_url_prefix + path + \"?v=\" + version_hash\n        return static_url_prefix + path\n\n    @classmethod\n    def get_version(cls, settings, path):\n        \"\"\"Generate the version string to be used in static URLs.\n\n        This method may be overridden in subclasses (but note that it\n        is a class method rather than a static method).  The default\n        implementation uses a hash of the file's contents.\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        abs_path = os.path.join(settings[\"static_path\"], path)\n        with cls._lock:\n            hashes = cls._static_hashes\n            if abs_path not in hashes:\n                try:\n                    f = open(abs_path, \"rb\")\n                    hashes[abs_path] = hashlib.md5(f.read()).hexdigest()\n                    f.close()\n                except Exception:\n                    gen_log.error(\"Could not open static file %r\", path)\n                    hashes[abs_path] = None\n            hsh = hashes.get(abs_path)\n            if hsh:\n                return hsh[:5]\n        return None\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        if os.path.sep != \"/\":\n            url_path = url_path.replace(\"/\", os.path.sep)\n        return url_path\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 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)))\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\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 `_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 `_modules` to avoid\n        # possible conflicts.\n        self.ui[\"_modules\"] = ObjectDict((n, self._ui_module(n, m)) for n, m in\n                                         application.ui_modules.items())\n        self.ui[\"modules\"] = self.ui[\"_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        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.gmtime()),\n        })\n        self.set_default_headers()\n        if not self.request.supports_http_1_1():\n            if self.request.headers.get(\"Connection\") == \"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    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 re.search(br\"[\\x00-\\x1f]\", 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 throw an HTTP 400 exception 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 HTTPError(400, \"Missing argument %s\" % 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        # Remove whitespace\n        url = re.sub(br\"[\\x00-\\x20]+\", \"\", utf8(url))\n        self.set_header(\"Location\", urlparse.urljoin(utf8(self.request.uri),\n                                                     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            raise Exception(\"WSGI applications do not support flush()\")\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                etag = self.compute_etag()\n                if etag is not None:\n                    self.set_header(\"Etag\", etag)\n                    inm = self.request.headers.get(\"If-None-Match\")\n                    if inm and inm.find(etag) != -1:\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\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    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):\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        We append ``?v=<signature>`` to the returned URL, which makes our\n        static file handler set an infinite expiration header on the\n        returned content. The signature is based on the content of the\n        file.\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        self.require_setting(\"static_path\", \"static_url\")\n        static_handler_class = self.settings.get(\n            \"static_handler_class\", StaticFileHandler)\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        return base + static_handler_class.make_static_url(self.settings, path)\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        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 _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.prepare()\n            if not self._finished:\n                getattr(self, self.request.method.lower())(\n                    *self.path_args, **self.path_kwargs)\n                if self._auto_finish and not self._finished:\n                    self.finish()\n        except Exception as e:\n            self._handle_request_exception(e)\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        if isinstance(e, HTTPError):\n            if e.log_message:\n                format = \"%d %s: \" + e.log_message\n                args = [e.status_code, self._request_summary()] + list(e.args)\n                gen_log.warning(format, *args)\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            app_log.error(\"Uncaught exception %s\\n%r\", self._request_summary(),\n                          self.request, exc_info=True)\n            self.send_error(500, exc_info=sys.exc_info())\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    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    \"\"\"\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, type(())):\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                        # 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 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    To map a path to this handler for a static data directory ``/var/www``,\n    you would add a line to your application like::\n\n        application = web.Application([\n            (r\"/static/(.*)\", web.StaticFileHandler, {\"path\": \"/var/www\"}),\n        ])\n\n    The local root directory of the content should be passed as the ``path``\n    argument to the handler.\n\n    To support aggressive browser caching, if the argument ``v`` is given\n    with the path, we set an infinite HTTP expiration header. So, if you\n    want browsers to cache a file indefinitely, send them to, e.g.,\n    ``/static/images/myimage.png?v=xxx``. Override `get_cache_time` method for\n    more fine-grained cache control.\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 = os.path.abspath(path) + os.path.sep\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        path = self.parse_url_path(path)\n        abspath = os.path.abspath(os.path.join(self.root, path))\n        # os.path.abspath strips a trailing /\n        # it needs to be temporarily added back for requests to root/\n        if not (abspath + os.path.sep).startswith(self.root):\n            raise HTTPError(403, \"%s is not in root static directory\", path)\n        if os.path.isdir(abspath) and 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 + \"/\")\n                return\n            abspath = os.path.join(abspath, self.default_filename)\n        if not os.path.exists(abspath):\n            raise HTTPError(404)\n        if not os.path.isfile(abspath):\n            raise HTTPError(403, \"%s is not a file\", path)\n\n        stat_result = os.stat(abspath)\n        modified = datetime.datetime.fromtimestamp(stat_result[stat.ST_MTIME])\n\n        self.set_header(\"Last-Modified\", modified)\n\n        mime_type, encoding = mimetypes.guess_type(abspath)\n        if mime_type:\n            self.set_header(\"Content-Type\", mime_type)\n\n        cache_time = self.get_cache_time(path, modified, mime_type)\n\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(path)\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_since = datetime.datetime.fromtimestamp(time.mktime(date_tuple))\n            if if_since >= modified:\n                self.set_status(304)\n                return\n\n        with open(abspath, \"rb\") as file:\n            data = file.read()\n            if include_body:\n                self.write(data)\n            else:\n                assert self.request.method == \"HEAD\"\n                self.set_header(\"Content-Length\", len(data))\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):\n        \"\"\"Constructs a versioned url for the given path.\n\n        This method may be overridden in subclasses (but note that it is\n        a class method rather than an instance method).\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        static_url_prefix = settings.get('static_url_prefix', '/static/')\n        version_hash = cls.get_version(settings, path)\n        if version_hash:\n            return static_url_prefix + path + \"?v=\" + version_hash\n        return static_url_prefix + path\n\n    @classmethod\n    def get_version(cls, settings, path):\n        \"\"\"Generate the version string to be used in static URLs.\n\n        This method may be overridden in subclasses (but note that it\n        is a class method rather than a static method).  The default\n        implementation uses a hash of the file's contents.\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        abs_path = os.path.join(settings[\"static_path\"], path)\n        with cls._lock:\n            hashes = cls._static_hashes\n            if abs_path not in hashes:\n                try:\n                    f = open(abs_path, \"rb\")\n                    hashes[abs_path] = hashlib.md5(f.read()).hexdigest()\n                    f.close()\n                except Exception:\n                    gen_log.error(\"Could not open static file %r\", path)\n                    hashes[abs_path] = None\n            hsh = hashes.get(abs_path)\n            if hsh:\n                return hsh[:5]\n        return None\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        if os.path.sep != \"/\":\n            url_path = url_path.replace(\"/\", os.path.sep)\n        return url_path\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 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)))\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": "fa07094d",
                "new_commit_hash": "3293b539",
                "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": 73,
                            "length": 6
                        },
                        "new_range": {
                            "start": 73,
                            "length": 7
                        },
                        "section": "import traceback"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "import types",
                                "type": "context"
                            },
                            {
                                "content": "import uuid",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "from tornado.concurrent import Future",
                                "type": "added"
                            },
                            {
                                "content": "from tornado import escape",
                                "type": "context"
                            },
                            {
                                "content": "from tornado import httputil",
                                "type": "context"
                            },
                            {
                                "content": "from tornado import locale",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "tornado/web.py",
                            "type": "statement",
                            "name": "",
                            "content": "from tornado.concurrent import Future",
                            "ast_type_str": "ImportFrom",
                            "start_lineno": 76,
                            "end_lineno": 76,
                            "parent": null
                        }
                    ],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 1165,
                            "length": 6
                        },
                        "new_range": {
                            "start": 1166,
                            "length": 8
                        },
                        "section": "def asynchronous(method):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "              self.finish()",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    \"\"\"",
                                "type": "context"
                            },
                            {
                                "content": "    # Delay the IOLoop import because it's not available on app engine.",
                                "type": "added"
                            },
                            {
                                "content": "    from tornado.ioloop import IOLoop",
                                "type": "added"
                            },
                            {
                                "content": "    @functools.wraps(method)",
                                "type": "context"
                            },
                            {
                                "content": "    def wrapper(self, *args, **kwargs):",
                                "type": "context"
                            },
                            {
                                "content": "        if self.application._wsgi:",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/web.py",
                            "type": "function",
                            "name": "asynchronous",
                            "content": "def asynchronous(method):\n    \"\"\"Wrap request handler methods with this if they are 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    \"\"\"\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",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 1149,
                            "end_lineno": 1192,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 1172,
                            "length": 7
                        },
                        "new_range": {
                            "start": 1175,
                            "length": 20
                        },
                        "section": "def asynchronous(method):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        self._auto_finish = False",
                                "type": "context"
                            },
                            {
                                "content": "        with stack_context.ExceptionStackContext(",
                                "type": "context"
                            },
                            {
                                "content": "                self._stack_context_handle_exception):",
                                "type": "context"
                            },
                            {
                                "content": "            return method(self, *args, **kwargs)",
                                "type": "deleted"
                            },
                            {
                                "content": "            result = method(self, *args, **kwargs)",
                                "type": "added"
                            },
                            {
                                "content": "            if isinstance(result, Future):",
                                "type": "added"
                            },
                            {
                                "content": "                # If @asynchronous is used with @gen.coroutine, (but",
                                "type": "added"
                            },
                            {
                                "content": "                # not @gen.engine), we can automatically finish the",
                                "type": "added"
                            },
                            {
                                "content": "                # request when the future resolves.  Additionally,",
                                "type": "added"
                            },
                            {
                                "content": "                # the Future will swallow any exceptions so we need",
                                "type": "added"
                            },
                            {
                                "content": "                # to throw them back out to the stack context to finish",
                                "type": "added"
                            },
                            {
                                "content": "                # the request.",
                                "type": "added"
                            },
                            {
                                "content": "                def future_complete(f):",
                                "type": "added"
                            },
                            {
                                "content": "                    f.result()",
                                "type": "added"
                            },
                            {
                                "content": "                    if not self._finished:",
                                "type": "added"
                            },
                            {
                                "content": "                        self.finish()",
                                "type": "added"
                            },
                            {
                                "content": "                IOLoop.current().add_future(result, future_complete)",
                                "type": "added"
                            },
                            {
                                "content": "            return result",
                                "type": "added"
                            },
                            {
                                "content": "    return wrapper",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/web.py",
                            "type": "function",
                            "name": "asynchronous",
                            "content": "def asynchronous(method):\n    \"\"\"Wrap request handler methods with this if they are 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    \"\"\"\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            return method(self, *args, **kwargs)\n    return wrapper",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 1148,
                            "end_lineno": 1176,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "e00e4c61fe2523224887fa0530fe780213c4296d^",
    "new_commit_hash": "e00e4c61fe2523224887fa0530fe780213c4296d",
    "commit_message": "Fix error handling with the combination of @asynchronous and @gen.coroutine.\n\nAlso make self.finish() optional for coroutines since we can finish\nif the future resolves successfully.",
    "commit_date": "2013-03-23T21:25:14-04:00",
    "metadata": {}
}
{
    "repo_name": "tornado",
    "new_commit_hash": "e00e4c61fe2523224887fa0530fe780213c4296d",
    "test_file_codes": [
        "from __future__ import absolute_import, division, print_function, with_statement\n\nimport contextlib\nimport functools\nimport sys\nimport textwrap\nimport time\n\nfrom tornado.concurrent import return_future\nfrom tornado.escape import url_escape\nfrom tornado.httpclient import AsyncHTTPClient\nfrom tornado.log import app_log\nfrom tornado import stack_context\nfrom tornado.testing import AsyncHTTPTestCase, AsyncTestCase, ExpectLog, gen_test\nfrom tornado.test.util import unittest, skipOnTravis\nfrom tornado.web import Application, RequestHandler, asynchronous\n\nfrom tornado import gen\n\n\nskipBefore33 = unittest.skipIf(sys.version_info < (3, 3), 'PEP 380 not available')\n\n\nclass GenEngineTest(AsyncTestCase):\n    def setUp(self):\n        super(GenEngineTest, self).setUp()\n        self.named_contexts = []\n\n    def named_context(self, name):\n        @contextlib.contextmanager\n        def context():\n            self.named_contexts.append(name)\n            try:\n                yield\n            finally:\n                self.assertEqual(self.named_contexts.pop(), name)\n        return context\n\n    def run_gen(self, f):\n        f()\n        return self.wait()\n\n    def delay_callback(self, iterations, callback, arg):\n        \"\"\"Runs callback(arg) after a number of IOLoop iterations.\"\"\"\n        if iterations == 0:\n            callback(arg)\n        else:\n            self.io_loop.add_callback(functools.partial(\n                self.delay_callback, iterations - 1, callback, arg))\n\n    @return_future\n    def async_future(self, result, callback):\n        self.io_loop.add_callback(callback, result)\n\n    def test_no_yield(self):\n        @gen.engine\n        def f():\n            self.stop()\n        self.run_gen(f)\n\n    def test_inline_cb(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))()\n            res = yield gen.Wait(\"k1\")\n            self.assertTrue(res is None)\n            self.stop()\n        self.run_gen(f)\n\n    def test_ioloop_cb(self):\n        @gen.engine\n        def f():\n            self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n            yield gen.Wait(\"k1\")\n            self.stop()\n        self.run_gen(f)\n\n    def test_exception_phase1(self):\n        @gen.engine\n        def f():\n            1 / 0\n        self.assertRaises(ZeroDivisionError, self.run_gen, f)\n\n    def test_exception_phase2(self):\n        @gen.engine\n        def f():\n            self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n            yield gen.Wait(\"k1\")\n            1 / 0\n        self.assertRaises(ZeroDivisionError, self.run_gen, f)\n\n    def test_exception_in_task_phase1(self):\n        def fail_task(callback):\n            1 / 0\n\n        @gen.engine\n        def f():\n            try:\n                yield gen.Task(fail_task)\n                raise Exception(\"did not get expected exception\")\n            except ZeroDivisionError:\n                self.stop()\n        self.run_gen(f)\n\n    def test_exception_in_task_phase2(self):\n        # This is the case that requires the use of stack_context in gen.engine\n        def fail_task(callback):\n            self.io_loop.add_callback(lambda: 1 / 0)\n\n        @gen.engine\n        def f():\n            try:\n                yield gen.Task(fail_task)\n                raise Exception(\"did not get expected exception\")\n            except ZeroDivisionError:\n                self.stop()\n        self.run_gen(f)\n\n    def test_with_arg(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))(42)\n            res = yield gen.Wait(\"k1\")\n            self.assertEqual(42, res)\n            self.stop()\n        self.run_gen(f)\n\n    def test_key_reuse(self):\n        @gen.engine\n        def f():\n            yield gen.Callback(\"k1\")\n            yield gen.Callback(\"k1\")\n            self.stop()\n        self.assertRaises(gen.KeyReuseError, self.run_gen, f)\n\n    def test_key_mismatch(self):\n        @gen.engine\n        def f():\n            yield gen.Callback(\"k1\")\n            yield gen.Wait(\"k2\")\n            self.stop()\n        self.assertRaises(gen.UnknownKeyError, self.run_gen, f)\n\n    def test_leaked_callback(self):\n        @gen.engine\n        def f():\n            yield gen.Callback(\"k1\")\n            self.stop()\n        self.assertRaises(gen.LeakedCallbackError, self.run_gen, f)\n\n    def test_parallel_callback(self):\n        @gen.engine\n        def f():\n            for k in range(3):\n                self.io_loop.add_callback((yield gen.Callback(k)))\n            yield gen.Wait(1)\n            self.io_loop.add_callback((yield gen.Callback(3)))\n            yield gen.Wait(0)\n            yield gen.Wait(3)\n            yield gen.Wait(2)\n            self.stop()\n        self.run_gen(f)\n\n    def test_bogus_yield(self):\n        @gen.engine\n        def f():\n            yield 42\n        self.assertRaises(gen.BadYieldError, self.run_gen, f)\n\n    def test_reuse(self):\n        @gen.engine\n        def f():\n            self.io_loop.add_callback((yield gen.Callback(0)))\n            yield gen.Wait(0)\n            self.stop()\n        self.run_gen(f)\n        self.run_gen(f)\n\n    def test_task(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            self.stop()\n        self.run_gen(f)\n\n    def test_wait_all(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))(\"v1\")\n            (yield gen.Callback(\"k2\"))(\"v2\")\n            results = yield gen.WaitAll([\"k1\", \"k2\"])\n            self.assertEqual(results, [\"v1\", \"v2\"])\n            self.stop()\n        self.run_gen(f)\n\n    def test_exception_in_yield(self):\n        @gen.engine\n        def f():\n            try:\n                yield gen.Wait(\"k1\")\n                raise Exception(\"did not get expected exception\")\n            except gen.UnknownKeyError:\n                pass\n            self.stop()\n        self.run_gen(f)\n\n    def test_resume_after_exception_in_yield(self):\n        @gen.engine\n        def f():\n            try:\n                yield gen.Wait(\"k1\")\n                raise Exception(\"did not get expected exception\")\n            except gen.UnknownKeyError:\n                pass\n            (yield gen.Callback(\"k2\"))(\"v2\")\n            self.assertEqual((yield gen.Wait(\"k2\")), \"v2\")\n            self.stop()\n        self.run_gen(f)\n\n    def test_orphaned_callback(self):\n        @gen.engine\n        def f():\n            self.orphaned_callback = yield gen.Callback(1)\n        try:\n            self.run_gen(f)\n            raise Exception(\"did not get expected exception\")\n        except gen.LeakedCallbackError:\n            pass\n        self.orphaned_callback()\n\n    def test_multi(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))(\"v1\")\n            (yield gen.Callback(\"k2\"))(\"v2\")\n            results = yield [gen.Wait(\"k1\"), gen.Wait(\"k2\")]\n            self.assertEqual(results, [\"v1\", \"v2\"])\n            self.stop()\n        self.run_gen(f)\n\n    def test_multi_delayed(self):\n        @gen.engine\n        def f():\n            # callbacks run at different times\n            responses = yield [\n                gen.Task(self.delay_callback, 3, arg=\"v1\"),\n                gen.Task(self.delay_callback, 1, arg=\"v2\"),\n            ]\n            self.assertEqual(responses, [\"v1\", \"v2\"])\n            self.stop()\n        self.run_gen(f)\n\n    @skipOnTravis\n    @gen_test\n    def test_multi_performance(self):\n        # Yielding a list used to have quadratic performance; make\n        # sure a large list stays reasonable.  On my laptop a list of\n        # 2000 used to take 1.8s, now it takes 0.12.\n        start = time.time()\n        yield [gen.Task(self.io_loop.add_callback) for i in range(2000)]\n        end = time.time()\n        self.assertLess(end - start, 1.0)\n\n    @gen_test\n    def test_future(self):\n        result = yield self.async_future(1)\n        self.assertEqual(result, 1)\n\n    @gen_test\n    def test_multi_future(self):\n        results = yield [self.async_future(1), self.async_future(2)]\n        self.assertEqual(results, [1, 2])\n\n    def test_arguments(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"noargs\"))()\n            self.assertEqual((yield gen.Wait(\"noargs\")), None)\n            (yield gen.Callback(\"1arg\"))(42)\n            self.assertEqual((yield gen.Wait(\"1arg\")), 42)\n\n            (yield gen.Callback(\"kwargs\"))(value=42)\n            result = yield gen.Wait(\"kwargs\")\n            self.assertTrue(isinstance(result, gen.Arguments))\n            self.assertEqual(((), dict(value=42)), result)\n            self.assertEqual(dict(value=42), result.kwargs)\n\n            (yield gen.Callback(\"2args\"))(42, 43)\n            result = yield gen.Wait(\"2args\")\n            self.assertTrue(isinstance(result, gen.Arguments))\n            self.assertEqual(((42, 43), {}), result)\n            self.assertEqual((42, 43), result.args)\n\n            def task_func(callback):\n                callback(None, error=\"foo\")\n            result = yield gen.Task(task_func)\n            self.assertTrue(isinstance(result, gen.Arguments))\n            self.assertEqual(((None,), dict(error=\"foo\")), result)\n\n            self.stop()\n        self.run_gen(f)\n\n    def test_stack_context_leak(self):\n        # regression test: repeated invocations of a gen-based\n        # function should not result in accumulated stack_contexts\n        @gen.engine\n        def inner(callback):\n            yield gen.Task(self.io_loop.add_callback)\n            callback()\n\n        @gen.engine\n        def outer():\n            for i in range(10):\n                yield gen.Task(inner)\n            stack_increase = len(stack_context._state.contexts) - initial_stack_depth\n            self.assertTrue(stack_increase <= 2)\n            self.stop()\n        initial_stack_depth = len(stack_context._state.contexts)\n        self.run_gen(outer)\n\n    def test_stack_context_leak_exception(self):\n        # same as previous, but with a function that exits with an exception\n        @gen.engine\n        def inner(callback):\n            yield gen.Task(self.io_loop.add_callback)\n            1 / 0\n\n        @gen.engine\n        def outer():\n            for i in range(10):\n                try:\n                    yield gen.Task(inner)\n                except ZeroDivisionError:\n                    pass\n            stack_increase = len(stack_context._state.contexts) - initial_stack_depth\n            self.assertTrue(stack_increase <= 2)\n            self.stop()\n        initial_stack_depth = len(stack_context._state.contexts)\n        self.run_gen(outer)\n\n    def function_with_stack_context(self, callback):\n        # Technically this function should stack_context.wrap its callback\n        # upon entry.  However, it is very common for this step to be\n        # omitted.\n        def step2():\n            self.assertEqual(self.named_contexts, ['a'])\n            self.io_loop.add_callback(callback)\n\n        with stack_context.StackContext(self.named_context('a')):\n            self.io_loop.add_callback(step2)\n\n    @gen_test\n    def test_wait_transfer_stack_context(self):\n        # Wait should not pick up contexts from where callback was invoked,\n        # even if that function improperly fails to wrap its callback.\n        cb = yield gen.Callback('k1')\n        self.function_with_stack_context(cb)\n        self.assertEqual(self.named_contexts, [])\n        yield gen.Wait('k1')\n        self.assertEqual(self.named_contexts, [])\n\n    @gen_test\n    def test_task_transfer_stack_context(self):\n        yield gen.Task(self.function_with_stack_context)\n        self.assertEqual(self.named_contexts, [])\n\n    def test_raise_after_stop(self):\n        # This pattern will be used in the following tests so make sure\n        # the exception propagates as expected.\n        @gen.engine\n        def f():\n            self.stop()\n            1 / 0\n\n        with self.assertRaises(ZeroDivisionError):\n            self.run_gen(f)\n\n    def test_sync_raise_return(self):\n        # gen.Return is allowed in @gen.engine, but it may not be used\n        # to return a value.\n        @gen.engine\n        def f():\n            self.stop(42)\n            raise gen.Return()\n\n        result = self.run_gen(f)\n        self.assertEqual(result, 42)\n\n    def test_async_raise_return(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            self.stop(42)\n            raise gen.Return()\n\n        result = self.run_gen(f)\n        self.assertEqual(result, 42)\n\n    def test_sync_raise_return_value(self):\n        @gen.engine\n        def f():\n            raise gen.Return(42)\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_async_raise_return_value(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            raise gen.Return(42)\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_return_value(self):\n        # It is an error to apply @gen.engine to a function that returns\n        # a value.\n        @gen.engine\n        def f():\n            return 42\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n\nclass GenCoroutineTest(AsyncTestCase):\n    def setUp(self):\n        # Stray StopIteration exceptions can lead to tests exiting prematurely,\n        # so we need explicit checks here to make sure the tests run all\n        # the way through.\n        self.finished = False\n        super(GenCoroutineTest, self).setUp()\n\n    def tearDown(self):\n        super(GenCoroutineTest, self).tearDown()\n        assert self.finished\n\n    @gen_test\n    def test_sync_gen_return(self):\n        @gen.coroutine\n        def f():\n            raise gen.Return(42)\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_async_gen_return(self):\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            raise gen.Return(42)\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_sync_return(self):\n        @gen.coroutine\n        def f():\n            return 42\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @skipBefore33\n    @gen_test\n    def test_async_return(self):\n        # It is a compile-time error to return a value in a generator\n        # before Python 3.3, so we must test this with exec.\n        # Flatten the real global and local namespace into our fake globals:\n        # it's all global from the perspective of f().\n        global_namespace = dict(globals(), **locals())\n        local_namespace = {}\n        exec(textwrap.dedent(\"\"\"\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            return 42\n        \"\"\"), global_namespace, local_namespace)\n        result = yield local_namespace['f']()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @skipBefore33\n    @gen_test\n    def test_async_early_return(self):\n        # A yield statement exists but is not executed, which means\n        # this function \"returns\" via an exception.  This exception\n        # doesn't happen before the exception handling is set up.\n        global_namespace = dict(globals(), **locals())\n        local_namespace = {}\n        exec(textwrap.dedent(\"\"\"\n        @gen.coroutine\n        def f():\n            if True:\n                return 42\n            yield gen.Task(self.io_loop.add_callback)\n        \"\"\"), global_namespace, local_namespace)\n        result = yield local_namespace['f']()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_sync_return_no_value(self):\n        @gen.coroutine\n        def f():\n            return\n        result = yield f()\n        self.assertEqual(result, None)\n        self.finished = True\n\n    @gen_test\n    def test_async_return_no_value(self):\n        # Without a return value we don't need python 3.3.\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            return\n        result = yield f()\n        self.assertEqual(result, None)\n        self.finished = True\n\n    @gen_test\n    def test_sync_raise(self):\n        @gen.coroutine\n        def f():\n            1 / 0\n        # The exception is raised when the future is yielded\n        # (or equivalently when its result method is called),\n        # not when the function itself is called).\n        future = f()\n        with self.assertRaises(ZeroDivisionError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_async_raise(self):\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            1 / 0\n        future = f()\n        with self.assertRaises(ZeroDivisionError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_pass_callback(self):\n        @gen.coroutine\n        def f():\n            raise gen.Return(42)\n        result = yield gen.Task(f)\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_replace_yieldpoint_exception(self):\n        # Test exception handling: a coroutine can catch one exception\n        # raised by a yield point and raise a different one.\n        @gen.coroutine\n        def f1():\n            1 / 0\n\n        @gen.coroutine\n        def f2():\n            try:\n                yield f1()\n            except ZeroDivisionError:\n                raise KeyError()\n\n        future = f2()\n        with self.assertRaises(KeyError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_swallow_yieldpoint_exception(self):\n        # Test exception handling: a coroutine can catch an exception\n        # raised by a yield point and not raise a different one.\n        @gen.coroutine\n        def f1():\n            1 / 0\n\n        @gen.coroutine\n        def f2():\n            try:\n                yield f1()\n            except ZeroDivisionError:\n                raise gen.Return(42)\n\n        result = yield f2()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_replace_context_exception(self):\n        # Test exception handling: exceptions thrown into the stack context\n        # can be caught and replaced.\n        @gen.coroutine\n        def f2():\n            self.io_loop.add_callback(lambda: 1 / 0)\n            try:\n                yield gen.Task(self.io_loop.add_timeout,\n                               self.io_loop.time() + 10)\n            except ZeroDivisionError:\n                raise KeyError()\n\n        future = f2()\n        with self.assertRaises(KeyError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_swallow_context_exception(self):\n        # Test exception handling: exceptions thrown into the stack context\n        # can be caught and ignored.\n        @gen.coroutine\n        def f2():\n            self.io_loop.add_callback(lambda: 1 / 0)\n            try:\n                yield gen.Task(self.io_loop.add_timeout,\n                               self.io_loop.time() + 10)\n            except ZeroDivisionError:\n                raise gen.Return(42)\n\n        result = yield f2()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n\nclass GenSequenceHandler(RequestHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        self.io_loop = self.request.connection.stream.io_loop\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.write(\"1\")\n        self.io_loop.add_callback((yield gen.Callback(\"k2\")))\n        yield gen.Wait(\"k2\")\n        self.write(\"2\")\n        # reuse an old key\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.finish(\"3\")\n\n\nclass GenCoroutineSequenceHandler(RequestHandler):\n    @asynchronous\n    @gen.coroutine\n    def get(self):\n        self.io_loop = self.request.connection.stream.io_loop\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.write(\"1\")\n        self.io_loop.add_callback((yield gen.Callback(\"k2\")))\n        yield gen.Wait(\"k2\")\n        self.write(\"2\")\n        # reuse an old key\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.finish(\"3\")\n\n\nclass GenCoroutineUnfinishedSequenceHandler(RequestHandler):\n    @asynchronous\n    @gen.coroutine\n    def get(self):\n        self.io_loop = self.request.connection.stream.io_loop\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.write(\"1\")\n        self.io_loop.add_callback((yield gen.Callback(\"k2\")))\n        yield gen.Wait(\"k2\")\n        self.write(\"2\")\n        # reuse an old key\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        # just write, don't finish\n        self.write(\"3\")\n\n\nclass GenTaskHandler(RequestHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        io_loop = self.request.connection.stream.io_loop\n        client = AsyncHTTPClient(io_loop=io_loop)\n        response = yield gen.Task(client.fetch, self.get_argument('url'))\n        response.rethrow()\n        self.finish(b\"got response: \" + response.body)\n\n\nclass GenExceptionHandler(RequestHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        # This test depends on the order of the two decorators.\n        io_loop = self.request.connection.stream.io_loop\n        yield gen.Task(io_loop.add_callback)\n        raise Exception(\"oops\")\n\n\nclass GenCoroutineExceptionHandler(RequestHandler):\n    @asynchronous\n    @gen.coroutine\n    def get(self):\n        # This test depends on the order of the two decorators.\n        io_loop = self.request.connection.stream.io_loop\n        yield gen.Task(io_loop.add_callback)\n        raise Exception(\"oops\")\n\n\nclass GenYieldExceptionHandler(RequestHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        io_loop = self.request.connection.stream.io_loop\n        # Test the interaction of the two stack_contexts.\n\n        def fail_task(callback):\n            io_loop.add_callback(lambda: 1 / 0)\n        try:\n            yield gen.Task(fail_task)\n            raise Exception(\"did not get expected exception\")\n        except ZeroDivisionError:\n            self.finish('ok')\n\n\nclass GenWebTest(AsyncHTTPTestCase):\n    def get_app(self):\n        return Application([\n            ('/sequence', GenSequenceHandler),\n            ('/coroutine_sequence', GenCoroutineSequenceHandler),\n            ('/coroutine_unfinished_sequence',\n             GenCoroutineUnfinishedSequenceHandler),\n            ('/task', GenTaskHandler),\n            ('/exception', GenExceptionHandler),\n            ('/coroutine_exception', GenCoroutineExceptionHandler),\n            ('/yield_exception', GenYieldExceptionHandler),\n        ])\n\n    def test_sequence_handler(self):\n        response = self.fetch('/sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_coroutine_sequence_handler(self):\n        response = self.fetch('/coroutine_sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_coroutine_unfinished_sequence_handler(self):\n        response = self.fetch('/coroutine_unfinished_sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_task_handler(self):\n        response = self.fetch('/task?url=%s' % url_escape(self.get_url('/sequence')))\n        self.assertEqual(response.body, b\"got response: 123\")\n\n    def test_exception_handler(self):\n        # Make sure we get an error and not a timeout\n        with ExpectLog(app_log, \"Uncaught exception GET /exception\"):\n            response = self.fetch('/exception')\n        self.assertEqual(500, response.code)\n\n    def test_coroutine_exception_handler(self):\n        # Make sure we get an error and not a timeout\n        with ExpectLog(app_log, \"Uncaught exception GET /coroutine_exception\"):\n            response = self.fetch('/coroutine_exception')\n        self.assertEqual(500, response.code)\n\n    def test_yield_exception_handler(self):\n        response = self.fetch('/yield_exception')\n        self.assertEqual(response.body, b'ok')\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 753ms\nPrepared 1 package in 683ms\nInstalled 1 package in 0.63ms\n + tornado==3.0b1 (from file:///home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e00e4c61fe2523224887fa0530fe780213c4296d)\nResolved 29 packages in 13ms\nInstalled 29 packages in 46ms\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": 0,
    "new_commit_res_stdout": "============================= test session starts =============================\nplatform linux -- Python 3.9.21\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e00e4c61fe2523224887fa0530fe780213c4296d\n........................................................\ncollected 56 items\n\n==================== short test summary info ====================\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_early_return\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_gen_return\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_raise\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_return\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_return_no_value\nPASSED r2e_tests.test_1::GenCoroutineTest::test_pass_callback\nPASSED r2e_tests.test_1::GenCoroutineTest::test_replace_context_exception\nPASSED r2e_tests.test_1::GenCoroutineTest::test_replace_yieldpoint_exception\nPASSED r2e_tests.test_1::GenCoroutineTest::test_swallow_context_exception\nPASSED r2e_tests.test_1::GenCoroutineTest::test_swallow_yieldpoint_exception\nPASSED r2e_tests.test_1::GenCoroutineTest::test_sync_gen_return\nPASSED r2e_tests.test_1::GenCoroutineTest::test_sync_raise\nPASSED r2e_tests.test_1::GenCoroutineTest::test_sync_return\nPASSED r2e_tests.test_1::GenCoroutineTest::test_sync_return_no_value\nPASSED r2e_tests.test_1::GenEngineTest::test_arguments\nPASSED r2e_tests.test_1::GenEngineTest::test_async_raise_return\nPASSED r2e_tests.test_1::GenEngineTest::test_async_raise_return_value\nPASSED r2e_tests.test_1::GenEngineTest::test_bogus_yield\nPASSED r2e_tests.test_1::GenEngineTest::test_exception_in_task_phase1\nPASSED r2e_tests.test_1::GenEngineTest::test_exception_in_task_phase2\nPASSED r2e_tests.test_1::GenEngineTest::test_exception_in_yield\nPASSED r2e_tests.test_1::GenEngineTest::test_exception_phase1\nPASSED r2e_tests.test_1::GenEngineTest::test_exception_phase2\nPASSED r2e_tests.test_1::GenEngineTest::test_future\nPASSED r2e_tests.test_1::GenEngineTest::test_inline_cb\nPASSED r2e_tests.test_1::GenEngineTest::test_ioloop_cb\nPASSED r2e_tests.test_1::GenEngineTest::test_key_mismatch\nPASSED r2e_tests.test_1::GenEngineTest::test_key_reuse\nPASSED r2e_tests.test_1::GenEngineTest::test_leaked_callback\nPASSED r2e_tests.test_1::GenEngineTest::test_multi\nPASSED r2e_tests.test_1::GenEngineTest::test_multi_delayed\nPASSED r2e_tests.test_1::GenEngineTest::test_multi_future\nPASSED r2e_tests.test_1::GenEngineTest::test_multi_performance\nPASSED r2e_tests.test_1::GenEngineTest::test_no_yield\nPASSED r2e_tests.test_1::GenEngineTest::test_orphaned_callback\nPASSED r2e_tests.test_1::GenEngineTest::test_parallel_callback\nPASSED r2e_tests.test_1::GenEngineTest::test_raise_after_stop\nPASSED r2e_tests.test_1::GenEngineTest::test_resume_after_exception_in_yield\nPASSED r2e_tests.test_1::GenEngineTest::test_return_value\nPASSED r2e_tests.test_1::GenEngineTest::test_reuse\nPASSED r2e_tests.test_1::GenEngineTest::test_stack_context_leak\nPASSED r2e_tests.test_1::GenEngineTest::test_stack_context_leak_exception\nPASSED r2e_tests.test_1::GenEngineTest::test_sync_raise_return\nPASSED r2e_tests.test_1::GenEngineTest::test_sync_raise_return_value\nPASSED r2e_tests.test_1::GenEngineTest::test_task\nPASSED r2e_tests.test_1::GenEngineTest::test_task_transfer_stack_context\nPASSED r2e_tests.test_1::GenEngineTest::test_wait_all\nPASSED r2e_tests.test_1::GenEngineTest::test_wait_transfer_stack_context\nPASSED r2e_tests.test_1::GenEngineTest::test_with_arg\nPASSED r2e_tests.test_1::GenWebTest::test_coroutine_exception_handler\nPASSED r2e_tests.test_1::GenWebTest::test_coroutine_sequence_handler\nPASSED r2e_tests.test_1::GenWebTest::test_coroutine_unfinished_sequence_handler\nPASSED r2e_tests.test_1::GenWebTest::test_exception_handler\nPASSED r2e_tests.test_1::GenWebTest::test_sequence_handler\nPASSED r2e_tests.test_1::GenWebTest::test_task_handler\nPASSED r2e_tests.test_1::GenWebTest::test_yield_exception_handler\n=================== 56 passed in 0.06s ===================\n",
    "new_commit_res_stderr": "ERROR:tornado.access:500 GET /coroutine_exception (127.0.0.1) 0.40ms\nERROR:tornado.access:500 GET /exception (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_e00e4c61fe2523224887fa0530fe780213c4296d\n........................................................\ncollected 56 items\n\n=================================== FAILURES ===================================\n__________ GenWebTest.test_coroutine_exception_handler __________\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_e00e4c61fe2523224887fa0530fe780213c4296d/r2e_tests/test_1.py\", line 770, in test_coroutine_exception_handler\n    response = self.fetch('/coroutine_exception')\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e00e4c61fe2523224887fa0530fe780213c4296d/tornado/testing.py\", line 296, in fetch\n    return self.wait()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e00e4c61fe2523224887fa0530fe780213c4296d/tornado/testing.py\", line 235, in wait\n    self.__rethrow()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e00e4c61fe2523224887fa0530fe780213c4296d/tornado/testing.py\", line 180, in __rethrow\n    raise_exc_info(failure)\n  File \"<string>\", line 3, in raise_exc_info\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e00e4c61fe2523224887fa0530fe780213c4296d/tornado/testing.py\", line 217, in timeout_func\n    raise self.failureException(\nAssertionError: Async operation timed out after 5 seconds\n__________ GenWebTest.test_coroutine_unfinished_sequence_handler __________\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_e00e4c61fe2523224887fa0530fe780213c4296d/r2e_tests/test_1.py\", line 754, in test_coroutine_unfinished_sequence_handler\n    response = self.fetch('/coroutine_unfinished_sequence')\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e00e4c61fe2523224887fa0530fe780213c4296d/tornado/testing.py\", line 296, in fetch\n    return self.wait()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e00e4c61fe2523224887fa0530fe780213c4296d/tornado/testing.py\", line 235, in wait\n    self.__rethrow()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e00e4c61fe2523224887fa0530fe780213c4296d/tornado/testing.py\", line 180, in __rethrow\n    raise_exc_info(failure)\n  File \"<string>\", line 3, in raise_exc_info\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e00e4c61fe2523224887fa0530fe780213c4296d/tornado/testing.py\", line 217, in timeout_func\n    raise self.failureException(\nAssertionError: Async operation timed out after 5 seconds\n\n==================== short test summary info ====================\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_early_return\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_gen_return\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_raise\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_return\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_return_no_value\nPASSED r2e_tests.test_1::GenCoroutineTest::test_pass_callback\nPASSED r2e_tests.test_1::GenCoroutineTest::test_replace_context_exception\nPASSED r2e_tests.test_1::GenCoroutineTest::test_replace_yieldpoint_exception\nPASSED r2e_tests.test_1::GenCoroutineTest::test_swallow_context_exception\nPASSED r2e_tests.test_1::GenCoroutineTest::test_swallow_yieldpoint_exception\nPASSED r2e_tests.test_1::GenCoroutineTest::test_sync_gen_return\nPASSED r2e_tests.test_1::GenCoroutineTest::test_sync_raise\nPASSED r2e_tests.test_1::GenCoroutineTest::test_sync_return\nPASSED r2e_tests.test_1::GenCoroutineTest::test_sync_return_no_value\nPASSED r2e_tests.test_1::GenEngineTest::test_arguments\nPASSED r2e_tests.test_1::GenEngineTest::test_async_raise_return\nPASSED r2e_tests.test_1::GenEngineTest::test_async_raise_return_value\nPASSED r2e_tests.test_1::GenEngineTest::test_bogus_yield\nPASSED r2e_tests.test_1::GenEngineTest::test_exception_in_task_phase1\nPASSED r2e_tests.test_1::GenEngineTest::test_exception_in_task_phase2\nPASSED r2e_tests.test_1::GenEngineTest::test_exception_in_yield\nPASSED r2e_tests.test_1::GenEngineTest::test_exception_phase1\nPASSED r2e_tests.test_1::GenEngineTest::test_exception_phase2\nPASSED r2e_tests.test_1::GenEngineTest::test_future\nPASSED r2e_tests.test_1::GenEngineTest::test_inline_cb\nPASSED r2e_tests.test_1::GenEngineTest::test_ioloop_cb\nPASSED r2e_tests.test_1::GenEngineTest::test_key_mismatch\nPASSED r2e_tests.test_1::GenEngineTest::test_key_reuse\nPASSED r2e_tests.test_1::GenEngineTest::test_leaked_callback\nPASSED r2e_tests.test_1::GenEngineTest::test_multi\nPASSED r2e_tests.test_1::GenEngineTest::test_multi_delayed\nPASSED r2e_tests.test_1::GenEngineTest::test_multi_future\nPASSED r2e_tests.test_1::GenEngineTest::test_multi_performance\nPASSED r2e_tests.test_1::GenEngineTest::test_no_yield\nPASSED r2e_tests.test_1::GenEngineTest::test_orphaned_callback\nPASSED r2e_tests.test_1::GenEngineTest::test_parallel_callback\nPASSED r2e_tests.test_1::GenEngineTest::test_raise_after_stop\nPASSED r2e_tests.test_1::GenEngineTest::test_resume_after_exception_in_yield\nPASSED r2e_tests.test_1::GenEngineTest::test_return_value\nPASSED r2e_tests.test_1::GenEngineTest::test_reuse\nPASSED r2e_tests.test_1::GenEngineTest::test_stack_context_leak\nPASSED r2e_tests.test_1::GenEngineTest::test_stack_context_leak_exception\nPASSED r2e_tests.test_1::GenEngineTest::test_sync_raise_return\nPASSED r2e_tests.test_1::GenEngineTest::test_sync_raise_return_value\nPASSED r2e_tests.test_1::GenEngineTest::test_task\nPASSED r2e_tests.test_1::GenEngineTest::test_task_transfer_stack_context\nPASSED r2e_tests.test_1::GenEngineTest::test_wait_all\nPASSED r2e_tests.test_1::GenEngineTest::test_wait_transfer_stack_context\nPASSED r2e_tests.test_1::GenEngineTest::test_with_arg\nFAILED r2e_tests.test_1::GenWebTest::test_coroutine_exception_handler\nPASSED r2e_tests.test_1::GenWebTest::test_coroutine_sequence_handler\nFAILED r2e_tests.test_1::GenWebTest::test_coroutine_unfinished_sequence_handler\nPASSED r2e_tests.test_1::GenWebTest::test_exception_handler\nPASSED r2e_tests.test_1::GenWebTest::test_sequence_handler\nPASSED r2e_tests.test_1::GenWebTest::test_task_handler\nPASSED r2e_tests.test_1::GenWebTest::test_yield_exception_handler\n=================== 2 failed, 54 passed in 10.10s ===================\n",
    "old_commit_res_stderr": "ERROR:tornado.access:500 GET /exception (127.0.0.1) 0.47ms\n"
}
tornado/test/gen_test.py tornado/web.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]

**Title:** Combining `@asynchronous` and `@gen.coroutine` Causes Requests to Hang Without Explicit Finish

**Description:**
When using the `@asynchronous` decorator in combination with `@gen.coroutine` in Tornado request handlers, the requests do not finish automatically upon successful completion of the coroutine. Additionally, exceptions raised within the coroutine are not properly handled, resulting in requests hanging and eventually timing out.

**Example Code:**
```python
from tornado.web import RequestHandler, asynchronous
from tornado import gen

class ExampleHandler(RequestHandler):
    @asynchronous
    @gen.coroutine
    def get(self):
        try:
            result = yield some_async_operation()
            self.write(result)
            # Missing self.finish()
        except Exception as e:
            self.set_status(500)
            self.write("Internal Server Error")
            # Missing self.finish()
```

**Expected Behavior:**
- The request should automatically finish after writing the response, even without an explicit call to `self.finish()`.
- In case of exceptions, the handler should respond with an appropriate error status without hanging.

**Actual Behavior:**
- Without calling `self.finish()`, the request does not complete, causing it to hang until it times out.
- Exceptions within the coroutine are not properly handled, leading to the same hanging behavior instead of responding with an error.

[/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 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 `_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 `_modules` to avoid
        # possible conflicts.
        self.ui["_modules"] = ObjectDict((n, self._ui_module(n, m)) for n, m in
                                         application.ui_modules.items())
        self.ui["modules"] = self.ui["_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.
        """
        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.gmtime()),
        })
        self.set_default_headers()
        if not self.request.supports_http_1_1():
            if self.request.headers.get("Connection") == "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]

    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 re.search(br"[\x00-\x1f]", 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 throw an HTTP 400 exception 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 HTTPError(400, "Missing argument %s" % 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)
        # Remove whitespace
        url = re.sub(br"[\x00-\x20]+", "", utf8(url))
        self.set_header("Location", urlparse.urljoin(utf8(self.request.uri),
                                                     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:
            raise Exception("WSGI applications do not support flush()")

        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):
                etag = self.compute_etag()
                if etag is not None:
                    self.set_header("Etag", etag)
                    inm = self.request.headers.get("If-None-Match")
                    if inm and inm.find(etag) != -1:
                        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()

    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

    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):
        """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).

        We append ``?v=<signature>`` to the returned URL, which makes our
        static file handler set an infinite expiration header on the
        returned content. The signature is based on the content of the
        file.

        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")
        static_handler_class = self.settings.get(
            "static_handler_class", StaticFileHandler)

        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 + static_handler_class.make_static_url(self.settings, path)

    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.

        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 _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.prepare()
            if not self._finished:
                getattr(self, self.request.method.lower())(
                    *self.path_args, **self.path_kwargs)
                if self._auto_finish and not self._finished:
                    self.finish()
        except Exception as e:
            self._handle_request_exception(e)

    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):
        if isinstance(e, HTTPError):
            if e.log_message:
                format = "%d %s: " + e.log_message
                args = [e.status_code, self._request_summary()] + list(e.args)
                gen_log.warning(format, *args)
            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:
            app_log.error("Uncaught exception %s\n%r", self._request_summary(),
                          self.request, exc_info=True)
            self.send_error(500, exc_info=sys.exc_info())

    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.

    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()

    """
    @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):
            return method(self, *args, **kwargs)
    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, type(())):
                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)
                        # 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 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.

    To map a path to this handler for a static data directory ``/var/www``,
    you would add a line to your application like::

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

    The local root directory of the content should be passed as the ``path``
    argument to the handler.

    To support aggressive browser caching, if the argument ``v`` is given
    with the path, we set an infinite HTTP expiration header. So, if you
    want browsers to cache a file indefinitely, send them to, e.g.,
    ``/static/images/myimage.png?v=xxx``. Override `get_cache_time` method for
    more fine-grained cache control.
    """
    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 = os.path.abspath(path) + os.path.sep
        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):
        path = self.parse_url_path(path)
        abspath = os.path.abspath(os.path.join(self.root, path))
        # os.path.abspath strips a trailing /
        # it needs to be temporarily added back for requests to root/
        if not (abspath + os.path.sep).startswith(self.root):
            raise HTTPError(403, "%s is not in root static directory", path)
        if os.path.isdir(abspath) 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 + "/")
                return
            abspath = os.path.join(abspath, self.default_filename)
        if not os.path.exists(abspath):
            raise HTTPError(404)
        if not os.path.isfile(abspath):
            raise HTTPError(403, "%s is not a file", path)

        stat_result = os.stat(abspath)
        modified = datetime.datetime.fromtimestamp(stat_result[stat.ST_MTIME])

        self.set_header("Last-Modified", modified)

        mime_type, encoding = mimetypes.guess_type(abspath)
        if mime_type:
            self.set_header("Content-Type", mime_type)

        cache_time = self.get_cache_time(path, modified, mime_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(path)

        # 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_since = datetime.datetime.fromtimestamp(time.mktime(date_tuple))
            if if_since >= modified:
                self.set_status(304)
                return

        with open(abspath, "rb") as file:
            data = file.read()
            if include_body:
                self.write(data)
            else:
                assert self.request.method == "HEAD"
                self.set_header("Content-Length", len(data))

    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):
        """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).

        ``settings`` is the `Application.settings` dictionary.  ``path``
        is the static path being requested.  The url returned should be
        relative to the current host.
        """
        static_url_prefix = settings.get('static_url_prefix', '/static/')
        version_hash = cls.get_version(settings, path)
        if version_hash:
            return static_url_prefix + path + "?v=" + version_hash
        return static_url_prefix + path

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

        This method may be overridden in subclasses (but note that it
        is a class method rather than a static method).  The default
        implementation uses a hash of the file's contents.

        ``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.
        """
        abs_path = os.path.join(settings["static_path"], path)
        with cls._lock:
            hashes = cls._static_hashes
            if abs_path not in hashes:
                try:
                    f = open(abs_path, "rb")
                    hashes[abs_path] = hashlib.md5(f.read()).hexdigest()
                    f.close()
                except Exception:
                    gen_log.error("Could not open static file %r", path)
                    hashes[abs_path] = None
            hsh = hashes.get(abs_path)
            if hsh:
                return hsh[:5]
        return None

    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``.
        """
        if os.path.sep != "/":
            url_path = url_path.replace("/", os.path.sep)
        return url_path


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 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)))
        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:** Combining `@asynchronous` and `@gen.coroutine` Causes Requests to Hang Without Explicit Finish

**Description:**
When using the `@asynchronous` decorator in combination with `@gen.coroutine` in Tornado request handlers, the requests do not finish automatically upon successful completion of the coroutine. Additionally, exceptions raised within the coroutine are not properly handled, resulting in requests hanging and eventually timing out.

**Example Code:**
```python
from tornado.web import RequestHandler, asynchronous
from tornado import gen

class ExampleHandler(RequestHandler):
    @asynchronous
    @gen.coroutine
    def get(self):
        try:
            result = yield some_async_operation()
            self.write(result)
            # Missing self.finish()
        except Exception as e:
            self.set_status(500)
            self.write("Internal Server Error")
            # Missing self.finish()
```

**Expected Behavior:**
- The request should automatically finish after writing the response, even without an explicit call to `self.finish()`.
- In case of exceptions, the handler should respond with an appropriate error status without hanging.

**Actual Behavior:**
- Without calling `self.finish()`, the request does not complete, causing it to hang until it times out.
- Exceptions within the coroutine are not properly handled, leading to the same hanging behavior instead of responding with an error.

[/ISSUE]
{
    "GenCoroutineTest.test_async_early_return": "PASSED",
    "GenCoroutineTest.test_async_gen_return": "PASSED",
    "GenCoroutineTest.test_async_raise": "PASSED",
    "GenCoroutineTest.test_async_return": "PASSED",
    "GenCoroutineTest.test_async_return_no_value": "PASSED",
    "GenCoroutineTest.test_pass_callback": "PASSED",
    "GenCoroutineTest.test_replace_context_exception": "PASSED",
    "GenCoroutineTest.test_replace_yieldpoint_exception": "PASSED",
    "GenCoroutineTest.test_swallow_context_exception": "PASSED",
    "GenCoroutineTest.test_swallow_yieldpoint_exception": "PASSED",
    "GenCoroutineTest.test_sync_gen_return": "PASSED",
    "GenCoroutineTest.test_sync_raise": "PASSED",
    "GenCoroutineTest.test_sync_return": "PASSED",
    "GenCoroutineTest.test_sync_return_no_value": "PASSED",
    "GenEngineTest.test_arguments": "PASSED",
    "GenEngineTest.test_async_raise_return": "PASSED",
    "GenEngineTest.test_async_raise_return_value": "PASSED",
    "GenEngineTest.test_bogus_yield": "PASSED",
    "GenEngineTest.test_exception_in_task_phase1": "PASSED",
    "GenEngineTest.test_exception_in_task_phase2": "PASSED",
    "GenEngineTest.test_exception_in_yield": "PASSED",
    "GenEngineTest.test_exception_phase1": "PASSED",
    "GenEngineTest.test_exception_phase2": "PASSED",
    "GenEngineTest.test_future": "PASSED",
    "GenEngineTest.test_inline_cb": "PASSED",
    "GenEngineTest.test_ioloop_cb": "PASSED",
    "GenEngineTest.test_key_mismatch": "PASSED",
    "GenEngineTest.test_key_reuse": "PASSED",
    "GenEngineTest.test_leaked_callback": "PASSED",
    "GenEngineTest.test_multi": "PASSED",
    "GenEngineTest.test_multi_delayed": "PASSED",
    "GenEngineTest.test_multi_future": "PASSED",
    "GenEngineTest.test_multi_performance": "PASSED",
    "GenEngineTest.test_no_yield": "PASSED",
    "GenEngineTest.test_orphaned_callback": "PASSED",
    "GenEngineTest.test_parallel_callback": "PASSED",
    "GenEngineTest.test_raise_after_stop": "PASSED",
    "GenEngineTest.test_resume_after_exception_in_yield": "PASSED",
    "GenEngineTest.test_return_value": "PASSED",
    "GenEngineTest.test_reuse": "PASSED",
    "GenEngineTest.test_stack_context_leak": "PASSED",
    "GenEngineTest.test_stack_context_leak_exception": "PASSED",
    "GenEngineTest.test_sync_raise_return": "PASSED",
    "GenEngineTest.test_sync_raise_return_value": "PASSED",
    "GenEngineTest.test_task": "PASSED",
    "GenEngineTest.test_task_transfer_stack_context": "PASSED",
    "GenEngineTest.test_wait_all": "PASSED",
    "GenEngineTest.test_wait_transfer_stack_context": "PASSED",
    "GenEngineTest.test_with_arg": "PASSED",
    "GenWebTest.test_coroutine_exception_handler": "PASSED",
    "GenWebTest.test_coroutine_sequence_handler": "PASSED",
    "GenWebTest.test_coroutine_unfinished_sequence_handler": "PASSED",
    "GenWebTest.test_exception_handler": "PASSED",
    "GenWebTest.test_sequence_handler": "PASSED",
    "GenWebTest.test_task_handler": "PASSED",
    "GenWebTest.test_yield_exception_handler": "PASSED"
}
diff --git a/tornado/web.py b/tornado/web.py
index fa07094d..3293b539 100644
--- a/tornado/web.py
+++ b/tornado/web.py
@@ -73,6 +73,7 @@ import traceback
 import types
 import uuid
 
+from tornado.concurrent import Future
 from tornado import escape
 from tornado import httputil
 from tornado import locale
@@ -1165,6 +1166,8 @@ def asynchronous(method):
               self.finish()
 
     """
+    # 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:
@@ -1172,7 +1175,20 @@ def asynchronous(method):
         self._auto_finish = False
         with stack_context.ExceptionStackContext(
                 self._stack_context_handle_exception):
-            return method(self, *args, **kwargs)
+            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
 
 
 

{"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\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 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 `_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 `_modules` to avoid\n        # possible conflicts.\n        self.ui[\"_modules\"] = ObjectDict((n, self._ui_module(n, m)) for n, m in\n                                         application.ui_modules.items())\n        self.ui[\"modules\"] = self.ui[\"_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        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.gmtime()),\n        })\n        self.set_default_headers()\n        if not self.request.supports_http_1_1():\n            if self.request.headers.get(\"Connection\") == \"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    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 re.search(br\"[\\x00-\\x1f]\", 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 throw an HTTP 400 exception 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 HTTPError(400, \"Missing argument %s\" % 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        # Remove whitespace\n        url = re.sub(br\"[\\x00-\\x20]+\", \"\", utf8(url))\n        self.set_header(\"Location\", urlparse.urljoin(utf8(self.request.uri),\n                                                     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            raise Exception(\"WSGI applications do not support flush()\")\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                etag = self.compute_etag()\n                if etag is not None:\n                    self.set_header(\"Etag\", etag)\n                    inm = self.request.headers.get(\"If-None-Match\")\n                    if inm and inm.find(etag) != -1:\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\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    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):\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        We append ``?v=<signature>`` to the returned URL, which makes our\n        static file handler set an infinite expiration header on the\n        returned content. The signature is based on the content of the\n        file.\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        self.require_setting(\"static_path\", \"static_url\")\n        static_handler_class = self.settings.get(\n            \"static_handler_class\", StaticFileHandler)\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        return base + static_handler_class.make_static_url(self.settings, path)\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        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 _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.prepare()\n            if not self._finished:\n                getattr(self, self.request.method.lower())(\n                    *self.path_args, **self.path_kwargs)\n                if self._auto_finish and not self._finished:\n                    self.finish()\n        except Exception as e:\n            self._handle_request_exception(e)\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        if isinstance(e, HTTPError):\n            if e.log_message:\n                format = \"%d %s: \" + e.log_message\n                args = [e.status_code, self._request_summary()] + list(e.args)\n                gen_log.warning(format, *args)\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            app_log.error(\"Uncaught exception %s\\n%r\", self._request_summary(),\n                          self.request, exc_info=True)\n            self.send_error(500, exc_info=sys.exc_info())\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    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    \"\"\"\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            return method(self, *args, **kwargs)\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, type(())):\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                        # 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 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    To map a path to this handler for a static data directory ``/var/www``,\n    you would add a line to your application like::\n\n        application = web.Application([\n            (r\"/static/(.*)\", web.StaticFileHandler, {\"path\": \"/var/www\"}),\n        ])\n\n    The local root directory of the content should be passed as the ``path``\n    argument to the handler.\n\n    To support aggressive browser caching, if the argument ``v`` is given\n    with the path, we set an infinite HTTP expiration header. So, if you\n    want browsers to cache a file indefinitely, send them to, e.g.,\n    ``/static/images/myimage.png?v=xxx``. Override `get_cache_time` method for\n    more fine-grained cache control.\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 = os.path.abspath(path) + os.path.sep\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        path = self.parse_url_path(path)\n        abspath = os.path.abspath(os.path.join(self.root, path))\n        # os.path.abspath strips a trailing /\n        # it needs to be temporarily added back for requests to root/\n        if not (abspath + os.path.sep).startswith(self.root):\n            raise HTTPError(403, \"%s is not in root static directory\", path)\n        if os.path.isdir(abspath) and 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 + \"/\")\n                return\n            abspath = os.path.join(abspath, self.default_filename)\n        if not os.path.exists(abspath):\n            raise HTTPError(404)\n        if not os.path.isfile(abspath):\n            raise HTTPError(403, \"%s is not a file\", path)\n\n        stat_result = os.stat(abspath)\n        modified = datetime.datetime.fromtimestamp(stat_result[stat.ST_MTIME])\n\n        self.set_header(\"Last-Modified\", modified)\n\n        mime_type, encoding = mimetypes.guess_type(abspath)\n        if mime_type:\n            self.set_header(\"Content-Type\", mime_type)\n\n        cache_time = self.get_cache_time(path, modified, mime_type)\n\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(path)\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_since = datetime.datetime.fromtimestamp(time.mktime(date_tuple))\n            if if_since >= modified:\n                self.set_status(304)\n                return\n\n        with open(abspath, \"rb\") as file:\n            data = file.read()\n            if include_body:\n                self.write(data)\n            else:\n                assert self.request.method == \"HEAD\"\n                self.set_header(\"Content-Length\", len(data))\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):\n        \"\"\"Constructs a versioned url for the given path.\n\n        This method may be overridden in subclasses (but note that it is\n        a class method rather than an instance method).\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        static_url_prefix = settings.get('static_url_prefix', '/static/')\n        version_hash = cls.get_version(settings, path)\n        if version_hash:\n            return static_url_prefix + path + \"?v=\" + version_hash\n        return static_url_prefix + path\n\n    @classmethod\n    def get_version(cls, settings, path):\n        \"\"\"Generate the version string to be used in static URLs.\n\n        This method may be overridden in subclasses (but note that it\n        is a class method rather than a static method).  The default\n        implementation uses a hash of the file's contents.\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        abs_path = os.path.join(settings[\"static_path\"], path)\n        with cls._lock:\n            hashes = cls._static_hashes\n            if abs_path not in hashes:\n                try:\n                    f = open(abs_path, \"rb\")\n                    hashes[abs_path] = hashlib.md5(f.read()).hexdigest()\n                    f.close()\n                except Exception:\n                    gen_log.error(\"Could not open static file %r\", path)\n                    hashes[abs_path] = None\n            hsh = hashes.get(abs_path)\n            if hsh:\n                return hsh[:5]\n        return None\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        if os.path.sep != \"/\":\n            url_path = url_path.replace(\"/\", os.path.sep)\n        return url_path\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 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)))\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:** Combining `@asynchronous` and `@gen.coroutine` Causes Requests to Hang Without Explicit Finish

**Description:**
When using the `@asynchronous` decorator in combination with `@gen.coroutine` in Tornado request handlers, the requests do not finish automatically upon successful completion of the coroutine. Additionally, exceptions raised within the coroutine are not properly handled, resulting in requests hanging and eventually timing out.

**Example Code:**
```python
from tornado.web import RequestHandler, asynchronous
from tornado import gen

class ExampleHandler(RequestHandler):
    @asynchronous
    @gen.coroutine
    def get(self):
        try:
            result = yield some_async_operation()
            self.write(result)
            # Missing self.finish()
        except Exception as e:
            self.set_status(500)
            self.write("Internal Server Error")
            # Missing self.finish()
```

**Expected Behavior:**
- The request should automatically finish after writing the response, even without an explicit call to `self.finish()`.
- In case of exceptions, the handler should respond with an appropriate error status without hanging.

**Actual Behavior:**
- Without calling `self.finish()`, the request does not complete, causing it to hang until it times out.
- Exceptions within the coroutine are not properly handled, leading to the same hanging behavior instead of responding with an error.

[/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 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 `_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 `_modules` to avoid
        # possible conflicts.
        self.ui["_modules"] = ObjectDict((n, self._ui_module(n, m)) for n, m in
                                         application.ui_modules.items())
        self.ui["modules"] = self.ui["_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.
        """
        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.gmtime()),
        })
        self.set_default_headers()
        if not self.request.supports_http_1_1():
            if self.request.headers.get("Connection") == "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]

    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 re.search(br"[\x00-\x1f]", 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 throw an HTTP 400 exception 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 HTTPError(400, "Missing argument %s" % 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)
        # Remove whitespace
        url = re.sub(br"[\x00-\x20]+", "", utf8(url))
        self.set_header("Location", urlparse.urljoin(utf8(self.request.uri),
                                                     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:
            raise Exception("WSGI applications do not support flush()")

        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):
                etag = self.compute_etag()
                if etag is not None:
                    self.set_header("Etag", etag)
                    inm = self.request.headers.get("If-None-Match")
                    if inm and inm.find(etag) != -1:
                        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()

    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

    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):
        """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).

        We append ``?v=<signature>`` to the returned URL, which makes our
        static file handler set an infinite expiration header on the
        returned content. The signature is based on the content of the
        file.

        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")
        static_handler_class = self.settings.get(
            "static_handler_class", StaticFileHandler)

        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 + static_handler_class.make_static_url(self.settings, path)

    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.

        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 _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.prepare()
            if not self._finished:
                getattr(self, self.request.method.lower())(
                    *self.path_args, **self.path_kwargs)
                if self._auto_finish and not self._finished:
                    self.finish()
        except Exception as e:
            self._handle_request_exception(e)

    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):
        if isinstance(e, HTTPError):
            if e.log_message:
                format = "%d %s: " + e.log_message
                args = [e.status_code, self._request_summary()] + list(e.args)
                gen_log.warning(format, *args)
            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:
            app_log.error("Uncaught exception %s\n%r", self._request_summary(),
                          self.request, exc_info=True)
            self.send_error(500, exc_info=sys.exc_info())

    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.

    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()

    """
    @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):
            return method(self, *args, **kwargs)
    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, type(())):
                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)
                        # 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 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.

    To map a path to this handler for a static data directory ``/var/www``,
    you would add a line to your application like::

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

    The local root directory of the content should be passed as the ``path``
    argument to the handler.

    To support aggressive browser caching, if the argument ``v`` is given
    with the path, we set an infinite HTTP expiration header. So, if you
    want browsers to cache a file indefinitely, send them to, e.g.,
    ``/static/images/myimage.png?v=xxx``. Override `get_cache_time` method for
    more fine-grained cache control.
    """
    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 = os.path.abspath(path) + os.path.sep
        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):
        path = self.parse_url_path(path)
        abspath = os.path.abspath(os.path.join(self.root, path))
        # os.path.abspath strips a trailing /
        # it needs to be temporarily added back for requests to root/
        if not (abspath + os.path.sep).startswith(self.root):
            raise HTTPError(403, "%s is not in root static directory", path)
        if os.path.isdir(abspath) 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 + "/")
                return
            abspath = os.path.join(abspath, self.default_filename)
        if not os.path.exists(abspath):
            raise HTTPError(404)
        if not os.path.isfile(abspath):
            raise HTTPError(403, "%s is not a file", path)

        stat_result = os.stat(abspath)
        modified = datetime.datetime.fromtimestamp(stat_result[stat.ST_MTIME])

        self.set_header("Last-Modified", modified)

        mime_type, encoding = mimetypes.guess_type(abspath)
        if mime_type:
            self.set_header("Content-Type", mime_type)

        cache_time = self.get_cache_time(path, modified, mime_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(path)

        # 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_since = datetime.datetime.fromtimestamp(time.mktime(date_tuple))
            if if_since >= modified:
                self.set_status(304)
                return

        with open(abspath, "rb") as file:
            data = file.read()
            if include_body:
                self.write(data)
            else:
                assert self.request.method == "HEAD"
                self.set_header("Content-Length", len(data))

    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):
        """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).

        ``settings`` is the `Application.settings` dictionary.  ``path``
        is the static path being requested.  The url returned should be
        relative to the current host.
        """
        static_url_prefix = settings.get('static_url_prefix', '/static/')
        version_hash = cls.get_version(settings, path)
        if version_hash:
            return static_url_prefix + path + "?v=" + version_hash
        return static_url_prefix + path

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

        This method may be overridden in subclasses (but note that it
        is a class method rather than a static method).  The default
        implementation uses a hash of the file's contents.

        ``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.
        """
        abs_path = os.path.join(settings["static_path"], path)
        with cls._lock:
            hashes = cls._static_hashes
            if abs_path not in hashes:
                try:
                    f = open(abs_path, "rb")
                    hashes[abs_path] = hashlib.md5(f.read()).hexdigest()
                    f.close()
                except Exception:
                    gen_log.error("Could not open static file %r", path)
                    hashes[abs_path] = None
            hsh = hashes.get(abs_path)
            if hsh:
                return hsh[:5]
        return None

    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``.
        """
        if os.path.sep != "/":
            url_path = url_path.replace("/", os.path.sep)
        return url_path


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 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)))
        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