{
    "file_diffs": [
        {
            "old_file_content": "# coding: utf-8\nfrom __future__ import absolute_import, division, print_function, with_statement\nimport re\nimport sys\nimport datetime\n\nimport tornado.escape\nfrom tornado.escape import utf8\nfrom tornado.util import raise_exc_info, Configurable, exec_in, ArgReplacer, timedelta_to_seconds, import_object, re_unescape\nfrom tornado.test.util import unittest\n\ntry:\n    from cStringIO import StringIO  # py2\nexcept ImportError:\n    from io import StringIO  # py3\n\n\nclass RaiseExcInfoTest(unittest.TestCase):\n    def test_two_arg_exception(self):\n        # This test would fail on python 3 if raise_exc_info were simply\n        # a three-argument raise statement, because TwoArgException\n        # doesn't have a \"copy constructor\"\n        class TwoArgException(Exception):\n            def __init__(self, a, b):\n                super(TwoArgException, self).__init__()\n                self.a, self.b = a, b\n\n        try:\n            raise TwoArgException(1, 2)\n        except TwoArgException:\n            exc_info = sys.exc_info()\n        try:\n            raise_exc_info(exc_info)\n            self.fail(\"didn't get expected exception\")\n        except TwoArgException as e:\n            self.assertIs(e, exc_info[1])\n\n\nclass TestConfigurable(Configurable):\n    @classmethod\n    def configurable_base(cls):\n        return TestConfigurable\n\n    @classmethod\n    def configurable_default(cls):\n        return TestConfig1\n\n\nclass TestConfig1(TestConfigurable):\n    def initialize(self, pos_arg=None, a=None):\n        self.a = a\n        self.pos_arg = pos_arg\n\n\nclass TestConfig2(TestConfigurable):\n    def initialize(self, pos_arg=None, b=None):\n        self.b = b\n        self.pos_arg = pos_arg\n\n\nclass ConfigurableTest(unittest.TestCase):\n    def setUp(self):\n        self.saved = TestConfigurable._save_configuration()\n\n    def tearDown(self):\n        TestConfigurable._restore_configuration(self.saved)\n\n    def checkSubclasses(self):\n        # no matter how the class is configured, it should always be\n        # possible to instantiate the subclasses directly\n        self.assertIsInstance(TestConfig1(), TestConfig1)\n        self.assertIsInstance(TestConfig2(), TestConfig2)\n\n        obj = TestConfig1(a=1)\n        self.assertEqual(obj.a, 1)\n        obj = TestConfig2(b=2)\n        self.assertEqual(obj.b, 2)\n\n    def test_default(self):\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertIs(obj.a, None)\n\n        obj = TestConfigurable(a=1)\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 1)\n\n        self.checkSubclasses()\n\n    def test_config_class(self):\n        TestConfigurable.configure(TestConfig2)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertIs(obj.b, None)\n\n        obj = TestConfigurable(b=2)\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 2)\n\n        self.checkSubclasses()\n\n    def test_config_args(self):\n        TestConfigurable.configure(None, a=3)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 3)\n\n        obj = TestConfigurable(42, a=4)\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 4)\n        self.assertEqual(obj.pos_arg, 42)\n\n        self.checkSubclasses()\n        # args bound in configure don't apply when using the subclass directly\n        obj = TestConfig1()\n        self.assertIs(obj.a, None)\n\n    def test_config_class_args(self):\n        TestConfigurable.configure(TestConfig2, b=5)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 5)\n\n        obj = TestConfigurable(42, b=6)\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 6)\n        self.assertEqual(obj.pos_arg, 42)\n\n        self.checkSubclasses()\n        # args bound in configure don't apply when using the subclass directly\n        obj = TestConfig2()\n        self.assertIs(obj.b, None)\n\n\nclass UnicodeLiteralTest(unittest.TestCase):\n    def test_unicode_escapes(self):\n        self.assertEqual(utf8(u'\\u00e9'), b'\\xc3\\xa9')\n\n\nclass ExecInTest(unittest.TestCase):\n    # This test is python 2 only because there are no new future imports\n    # defined in python 3 yet.\n    @unittest.skipIf(sys.version_info >= print_function.getMandatoryRelease(),\n                     'no testable future imports')\n    def test_no_inherit_future(self):\n        # This file has from __future__ import print_function...\n        f = StringIO()\n        print('hello', file=f)\n        # ...but the template doesn't\n        exec_in('print >> f, \"world\"', dict(f=f))\n        self.assertEqual(f.getvalue(), 'hello\\nworld\\n')\n\n\nclass ArgReplacerTest(unittest.TestCase):\n    def setUp(self):\n        def function(x, y, callback=None, z=None):\n            pass\n        self.replacer = ArgReplacer(function, 'callback')\n\n    def test_omitted(self):\n        args = (1, 2)\n        kwargs = dict()\n        self.assertIs(self.replacer.get_old_value(args, kwargs), None)\n        self.assertEqual(self.replacer.replace('new', args, kwargs),\n                         (None, (1, 2), dict(callback='new')))\n\n    def test_position(self):\n        args = (1, 2, 'old', 3)\n        kwargs = dict()\n        self.assertEqual(self.replacer.get_old_value(args, kwargs), 'old')\n        self.assertEqual(self.replacer.replace('new', args, kwargs),\n                         ('old', [1, 2, 'new', 3], dict()))\n\n    def test_keyword(self):\n        args = (1,)\n        kwargs = dict(y=2, callback='old', z=3)\n        self.assertEqual(self.replacer.get_old_value(args, kwargs), 'old')\n        self.assertEqual(self.replacer.replace('new', args, kwargs),\n                         ('old', (1,), dict(y=2, callback='new', z=3)))\n\n\nclass TimedeltaToSecondsTest(unittest.TestCase):\n    def test_timedelta_to_seconds(self):\n        time_delta = datetime.timedelta(hours=1)\n        self.assertEqual(timedelta_to_seconds(time_delta), 3600.0)\n\n\nclass ImportObjectTest(unittest.TestCase):\n    def test_import_member(self):\n        self.assertIs(import_object('tornado.escape.utf8'), utf8)\n\n    def test_import_member_unicode(self):\n        self.assertIs(import_object(u'tornado.escape.utf8'), utf8)\n\n    def test_import_module(self):\n        self.assertIs(import_object('tornado.escape'), tornado.escape)\n\n    def test_import_module_unicode(self):\n        # The internal implementation of __import__ differs depending on\n        # whether the thing being imported is a module or not.\n        # This variant requires a byte string in python 2.\n        self.assertIs(import_object(u'tornado.escape'), tornado.escape)\n\n\nclass ReUnescapeTest(unittest.TestCase):\n    def test_re_unescape(self):\n        test_strings = (\n            '/favicon.ico',\n            'index.html',\n            '\\x00\\x01\\\\000',\n            'Hello, World!',\n            '!$@#%;',\n        )\n        for string in test_strings:\n            self.assertEqual(string, re_unescape(re.escape(string)))\n",
            "new_file_content": "# coding: utf-8\nfrom __future__ import absolute_import, division, print_function, with_statement\nimport re\nimport sys\nimport datetime\n\nimport tornado.escape\nfrom tornado.escape import utf8\nfrom tornado.util import raise_exc_info, Configurable, exec_in, ArgReplacer, timedelta_to_seconds, import_object, re_unescape\nfrom tornado.test.util import unittest\n\ntry:\n    from cStringIO import StringIO  # py2\nexcept ImportError:\n    from io import StringIO  # py3\n\n\nclass RaiseExcInfoTest(unittest.TestCase):\n    def test_two_arg_exception(self):\n        # This test would fail on python 3 if raise_exc_info were simply\n        # a three-argument raise statement, because TwoArgException\n        # doesn't have a \"copy constructor\"\n        class TwoArgException(Exception):\n            def __init__(self, a, b):\n                super(TwoArgException, self).__init__()\n                self.a, self.b = a, b\n\n        try:\n            raise TwoArgException(1, 2)\n        except TwoArgException:\n            exc_info = sys.exc_info()\n        try:\n            raise_exc_info(exc_info)\n            self.fail(\"didn't get expected exception\")\n        except TwoArgException as e:\n            self.assertIs(e, exc_info[1])\n\n\nclass TestConfigurable(Configurable):\n    @classmethod\n    def configurable_base(cls):\n        return TestConfigurable\n\n    @classmethod\n    def configurable_default(cls):\n        return TestConfig1\n\n\nclass TestConfig1(TestConfigurable):\n    def initialize(self, pos_arg=None, a=None):\n        self.a = a\n        self.pos_arg = pos_arg\n\n\nclass TestConfig2(TestConfigurable):\n    def initialize(self, pos_arg=None, b=None):\n        self.b = b\n        self.pos_arg = pos_arg\n\n\nclass ConfigurableTest(unittest.TestCase):\n    def setUp(self):\n        self.saved = TestConfigurable._save_configuration()\n\n    def tearDown(self):\n        TestConfigurable._restore_configuration(self.saved)\n\n    def checkSubclasses(self):\n        # no matter how the class is configured, it should always be\n        # possible to instantiate the subclasses directly\n        self.assertIsInstance(TestConfig1(), TestConfig1)\n        self.assertIsInstance(TestConfig2(), TestConfig2)\n\n        obj = TestConfig1(a=1)\n        self.assertEqual(obj.a, 1)\n        obj = TestConfig2(b=2)\n        self.assertEqual(obj.b, 2)\n\n    def test_default(self):\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertIs(obj.a, None)\n\n        obj = TestConfigurable(a=1)\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 1)\n\n        self.checkSubclasses()\n\n    def test_config_class(self):\n        TestConfigurable.configure(TestConfig2)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertIs(obj.b, None)\n\n        obj = TestConfigurable(b=2)\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 2)\n\n        self.checkSubclasses()\n\n    def test_config_args(self):\n        TestConfigurable.configure(None, a=3)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 3)\n\n        obj = TestConfigurable(42, a=4)\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 4)\n        self.assertEqual(obj.pos_arg, 42)\n\n        self.checkSubclasses()\n        # args bound in configure don't apply when using the subclass directly\n        obj = TestConfig1()\n        self.assertIs(obj.a, None)\n\n    def test_config_class_args(self):\n        TestConfigurable.configure(TestConfig2, b=5)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 5)\n\n        obj = TestConfigurable(42, b=6)\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 6)\n        self.assertEqual(obj.pos_arg, 42)\n\n        self.checkSubclasses()\n        # args bound in configure don't apply when using the subclass directly\n        obj = TestConfig2()\n        self.assertIs(obj.b, None)\n\n\nclass UnicodeLiteralTest(unittest.TestCase):\n    def test_unicode_escapes(self):\n        self.assertEqual(utf8(u'\\u00e9'), b'\\xc3\\xa9')\n\n\nclass ExecInTest(unittest.TestCase):\n    # This test is python 2 only because there are no new future imports\n    # defined in python 3 yet.\n    @unittest.skipIf(sys.version_info >= print_function.getMandatoryRelease(),\n                     'no testable future imports')\n    def test_no_inherit_future(self):\n        # This file has from __future__ import print_function...\n        f = StringIO()\n        print('hello', file=f)\n        # ...but the template doesn't\n        exec_in('print >> f, \"world\"', dict(f=f))\n        self.assertEqual(f.getvalue(), 'hello\\nworld\\n')\n\n\nclass ArgReplacerTest(unittest.TestCase):\n    def setUp(self):\n        def function(x, y, callback=None, z=None):\n            pass\n        self.replacer = ArgReplacer(function, 'callback')\n\n    def test_omitted(self):\n        args = (1, 2)\n        kwargs = dict()\n        self.assertIs(self.replacer.get_old_value(args, kwargs), None)\n        self.assertEqual(self.replacer.replace('new', args, kwargs),\n                         (None, (1, 2), dict(callback='new')))\n\n    def test_position(self):\n        args = (1, 2, 'old', 3)\n        kwargs = dict()\n        self.assertEqual(self.replacer.get_old_value(args, kwargs), 'old')\n        self.assertEqual(self.replacer.replace('new', args, kwargs),\n                         ('old', [1, 2, 'new', 3], dict()))\n\n    def test_keyword(self):\n        args = (1,)\n        kwargs = dict(y=2, callback='old', z=3)\n        self.assertEqual(self.replacer.get_old_value(args, kwargs), 'old')\n        self.assertEqual(self.replacer.replace('new', args, kwargs),\n                         ('old', (1,), dict(y=2, callback='new', z=3)))\n\n\nclass TimedeltaToSecondsTest(unittest.TestCase):\n    def test_timedelta_to_seconds(self):\n        time_delta = datetime.timedelta(hours=1)\n        self.assertEqual(timedelta_to_seconds(time_delta), 3600.0)\n\n\nclass ImportObjectTest(unittest.TestCase):\n    def test_import_member(self):\n        self.assertIs(import_object('tornado.escape.utf8'), utf8)\n\n    def test_import_member_unicode(self):\n        self.assertIs(import_object(u'tornado.escape.utf8'), utf8)\n\n    def test_import_module(self):\n        self.assertIs(import_object('tornado.escape'), tornado.escape)\n\n    def test_import_module_unicode(self):\n        # The internal implementation of __import__ differs depending on\n        # whether the thing being imported is a module or not.\n        # This variant requires a byte string in python 2.\n        self.assertIs(import_object(u'tornado.escape'), tornado.escape)\n\n\nclass ReUnescapeTest(unittest.TestCase):\n    def test_re_unescape(self):\n        test_strings = (\n            '/favicon.ico',\n            'index.html',\n            'Hello, World!',\n            '!$@#%;',\n        )\n        for string in test_strings:\n            self.assertEqual(string, re_unescape(re.escape(string)))\n\n    def test_re_unescape_raises_error_on_invalid_input(self):\n        with self.assertRaises(ValueError):\n            re_unescape('\\\\d')\n        with self.assertRaises(ValueError):\n            re_unescape('\\\\b')\n        with self.assertRaises(ValueError):\n            re_unescape('\\\\Z')\n",
            "header": {
                "file": {
                    "path": "tornado/test/util_test.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "6a0fa5c4",
                "new_commit_hash": "70b6e7a1",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tornado/test/util_test.py"
            },
            "plus_file": {
                "path": "b/tornado/test/util_test.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 207,
                            "length": 9
                        },
                        "new_range": {
                            "start": 207,
                            "length": 16
                        },
                        "section": "class ReUnescapeTest(unittest.TestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        test_strings = (",
                                "type": "context"
                            },
                            {
                                "content": "            '/favicon.ico',",
                                "type": "context"
                            },
                            {
                                "content": "            'index.html',",
                                "type": "context"
                            },
                            {
                                "content": "            '\\x00\\x01\\\\000',",
                                "type": "deleted"
                            },
                            {
                                "content": "            'Hello, World!',",
                                "type": "context"
                            },
                            {
                                "content": "            '!$@#%;',",
                                "type": "context"
                            },
                            {
                                "content": "        )",
                                "type": "context"
                            },
                            {
                                "content": "        for string in test_strings:",
                                "type": "context"
                            },
                            {
                                "content": "            self.assertEqual(string, re_unescape(re.escape(string)))",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def test_re_unescape_raises_error_on_invalid_input(self):",
                                "type": "added"
                            },
                            {
                                "content": "        with self.assertRaises(ValueError):",
                                "type": "added"
                            },
                            {
                                "content": "            re_unescape('\\\\d')",
                                "type": "added"
                            },
                            {
                                "content": "        with self.assertRaises(ValueError):",
                                "type": "added"
                            },
                            {
                                "content": "            re_unescape('\\\\b')",
                                "type": "added"
                            },
                            {
                                "content": "        with self.assertRaises(ValueError):",
                                "type": "added"
                            },
                            {
                                "content": "            re_unescape('\\\\Z')",
                                "type": "added"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/test/util_test.py",
                            "type": "method",
                            "name": "ReUnescapeTest.test_re_unescape",
                            "content": "class ReUnescapeTest(unittest.TestCase):\n    def test_re_unescape(self):\n        test_strings = (\n            '/favicon.ico',\n            'index.html',\n            '\\x00\\x01\\\\000',\n            'Hello, World!',\n            '!$@#%;',\n        )\n        for string in test_strings:\n            self.assertEqual(string, re_unescape(re.escape(string)))",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 206,
                            "end_lineno": 215,
                            "parent": {
                                "file_name": "tornado/test/util_test.py",
                                "type": "class",
                                "name": "ReUnescapeTest",
                                "content": "class ReUnescapeTest(unittest.TestCase):\n    def test_re_unescape(self):\n        test_strings = (\n            '/favicon.ico',\n            'index.html',\n            '\\x00\\x01\\\\000',\n            'Hello, World!',\n            '!$@#%;',\n        )\n        for string in test_strings:\n            self.assertEqual(string, re_unescape(re.escape(string)))",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 205,
                                "end_lineno": 215,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/test/util_test.py",
                            "type": "class",
                            "name": "ReUnescapeTest",
                            "content": "class ReUnescapeTest(unittest.TestCase):\n    def test_re_unescape(self):\n        test_strings = (\n            '/favicon.ico',\n            'index.html',\n            '\\x00\\x01\\\\000',\n            'Hello, World!',\n            '!$@#%;',\n        )\n        for string in test_strings:\n            self.assertEqual(string, re_unescape(re.escape(string)))",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 205,
                            "end_lineno": 215,
                            "parent": null
                        }
                    ],
                    "added_entities": [
                        {
                            "file_name": "tornado/test/util_test.py",
                            "type": "method",
                            "name": "ReUnescapeTest.test_re_unescape_raises_error_on_invalid_input",
                            "content": "class ReUnescapeTest(unittest.TestCase):\n    def test_re_unescape(self):\n        test_strings = (\n            '/favicon.ico',\n            'index.html',\n            'Hello, World!',\n            '!$@#%;',\n        )\n        for string in test_strings:\n            self.assertEqual(string, re_unescape(re.escape(string)))\n\n    def test_re_unescape_raises_error_on_invalid_input(self):\n        with self.assertRaises(ValueError):\n            re_unescape('\\\\d')\n        with self.assertRaises(ValueError):\n            re_unescape('\\\\b')\n        with self.assertRaises(ValueError):\n            re_unescape('\\\\Z')",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 216,
                            "end_lineno": 222,
                            "parent": {
                                "file_name": "tornado/test/util_test.py",
                                "type": "class",
                                "name": "ReUnescapeTest",
                                "content": "class ReUnescapeTest(unittest.TestCase):\n    def test_re_unescape(self):\n        test_strings = (\n            '/favicon.ico',\n            'index.html',\n            'Hello, World!',\n            '!$@#%;',\n        )\n        for string in test_strings:\n            self.assertEqual(string, re_unescape(re.escape(string)))\n\n    def test_re_unescape_raises_error_on_invalid_input(self):\n        with self.assertRaises(ValueError):\n            re_unescape('\\\\d')\n        with self.assertRaises(ValueError):\n            re_unescape('\\\\b')\n        with self.assertRaises(ValueError):\n            re_unescape('\\\\Z')",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 205,
                                "end_lineno": 222,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "\"\"\"Miscellaneous utility functions and classes.\n\nThis module is used internally by Tornado.  It is not necessarily expected\nthat the functions and classes defined here will be useful to other\napplications, but they are documented here in case they are.\n\nThe one public-facing part of this module is the `Configurable` class\nand its `~Configurable.configure` method, which becomes a part of the\ninterface of its subclasses, including `.AsyncHTTPClient`, `.IOLoop`,\nand `.Resolver`.\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nimport array\nimport os\nimport re\nimport sys\nimport zlib\n\n\ntry:\n    xrange  # py2\nexcept NameError:\n    xrange = range  # py3\n\n# inspect.getargspec() raises DeprecationWarnings in Python 3.5.\n# The two functions have compatible interfaces for the parts we need.\ntry:\n    from inspect import getfullargspec as getargspec  # py3\nexcept ImportError:\n    from inspect import getargspec  # py2\n\n\nclass ObjectDict(dict):\n    \"\"\"Makes a dictionary behave like an object, with attribute-style access.\n    \"\"\"\n    def __getattr__(self, name):\n        try:\n            return self[name]\n        except KeyError:\n            raise AttributeError(name)\n\n    def __setattr__(self, name, value):\n        self[name] = value\n\n\nclass GzipDecompressor(object):\n    \"\"\"Streaming gzip decompressor.\n\n    The interface is like that of `zlib.decompressobj` (without some of the\n    optional arguments, but it understands gzip headers and checksums.\n    \"\"\"\n    def __init__(self):\n        # Magic parameter makes zlib module understand gzip header\n        # http://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib\n        # This works on cpython and pypy, but not jython.\n        self.decompressobj = zlib.decompressobj(16 + zlib.MAX_WBITS)\n\n    def decompress(self, value, max_length=None):\n        \"\"\"Decompress a chunk, returning newly-available data.\n\n        Some data may be buffered for later processing; `flush` must\n        be called when there is no more input data to ensure that\n        all data was processed.\n\n        If ``max_length`` is given, some input data may be left over\n        in ``unconsumed_tail``; you must retrieve this value and pass\n        it back to a future call to `decompress` if it is not empty.\n        \"\"\"\n        return self.decompressobj.decompress(value, max_length)\n\n    @property\n    def unconsumed_tail(self):\n        \"\"\"Returns the unconsumed portion left over\n        \"\"\"\n        return self.decompressobj.unconsumed_tail\n\n    def flush(self):\n        \"\"\"Return any remaining buffered data not yet returned by decompress.\n\n        Also checks for errors such as truncated input.\n        No other methods may be called on this object after `flush`.\n        \"\"\"\n        return self.decompressobj.flush()\n\n\nif not isinstance(b'', type('')):\n    unicode_type = str\n    basestring_type = str\nelse:\n    # These names don't exist in py3, so use noqa comments to disable\n    # warnings in flake8.\n    unicode_type = unicode  # noqa\n    basestring_type = basestring  # noqa\n\n\ndef import_object(name):\n    \"\"\"Imports an object by name.\n\n    import_object('x') is equivalent to 'import x'.\n    import_object('x.y.z') is equivalent to 'from x.y import z'.\n\n    >>> import tornado.escape\n    >>> import_object('tornado.escape') is tornado.escape\n    True\n    >>> import_object('tornado.escape.utf8') is tornado.escape.utf8\n    True\n    >>> import_object('tornado') is tornado\n    True\n    >>> import_object('tornado.missing_module')\n    Traceback (most recent call last):\n        ...\n    ImportError: No module named missing_module\n    \"\"\"\n    if isinstance(name, unicode_type) and str is not unicode_type:\n        # On python 2 a byte string is required.\n        name = name.encode('utf-8')\n    if name.count('.') == 0:\n        return __import__(name, None, None)\n\n    parts = name.split('.')\n    obj = __import__('.'.join(parts[:-1]), None, None, [parts[-1]], 0)\n    try:\n        return getattr(obj, parts[-1])\n    except AttributeError:\n        raise ImportError(\"No module named %s\" % parts[-1])\n\n\n# Deprecated alias that was used before we dropped py25 support.\n# Left here in case anyone outside Tornado is using it.\nbytes_type = bytes\n\nif sys.version_info > (3,):\n    exec(\"\"\"\ndef raise_exc_info(exc_info):\n    raise exc_info[1].with_traceback(exc_info[2])\n\ndef exec_in(code, glob, loc=None):\n    if isinstance(code, str):\n        code = compile(code, '<string>', 'exec', dont_inherit=True)\n    exec(code, glob, loc)\n\"\"\")\nelse:\n    exec(\"\"\"\ndef raise_exc_info(exc_info):\n    raise exc_info[0], exc_info[1], exc_info[2]\n\ndef exec_in(code, glob, loc=None):\n    if isinstance(code, basestring):\n        # exec(string) inherits the caller's future imports; compile\n        # the string first to prevent that.\n        code = compile(code, '<string>', 'exec', dont_inherit=True)\n    exec code in glob, loc\n\"\"\")\n\n\ndef errno_from_exception(e):\n    \"\"\"Provides the errno from an Exception object.\n\n    There are cases that the errno attribute was not set so we pull\n    the errno out of the args but if someone instantiates an Exception\n    without any args you will get a tuple error. So this function\n    abstracts all that behavior to give you a safe way to get the\n    errno.\n    \"\"\"\n\n    if hasattr(e, 'errno'):\n        return e.errno\n    elif e.args:\n        return e.args[0]\n    else:\n        return None\n\n\n_re_unescape_split_pattern = re.compile(r'(\\\\[^0])')\n# re.escape('\\x00') is a special case\n\ndef re_unescape(s):\n    '''\n    unescape a string escaped by ``re.escape()``\n    '''\n    parts = []\n    for i, splited in enumerate(_re_unescape_split_pattern.split(s)):\n        if i % 2:\n            parts.append(splited[1])\n        else:\n            parts.append(splited.replace(r'\\000', '\\000'))\n    return ''.join(parts)\n\n\nclass Configurable(object):\n    \"\"\"Base class for configurable interfaces.\n\n    A configurable interface is an (abstract) class whose constructor\n    acts as a factory function for one of its implementation subclasses.\n    The implementation subclass as well as optional keyword arguments to\n    its initializer can be set globally at runtime with `configure`.\n\n    By using the constructor as the factory method, the interface\n    looks like a normal class, `isinstance` works as usual, etc.  This\n    pattern is most useful when the choice of implementation is likely\n    to be a global decision (e.g. when `~select.epoll` is available,\n    always use it instead of `~select.select`), or when a\n    previously-monolithic class has been split into specialized\n    subclasses.\n\n    Configurable subclasses must define the class methods\n    `configurable_base` and `configurable_default`, and use the instance\n    method `initialize` instead of ``__init__``.\n    \"\"\"\n    __impl_class = None\n    __impl_kwargs = None\n\n    def __new__(cls, *args, **kwargs):\n        base = cls.configurable_base()\n        init_kwargs = {}\n        if cls is base:\n            impl = cls.configured_class()\n            if base.__impl_kwargs:\n                init_kwargs.update(base.__impl_kwargs)\n        else:\n            impl = cls\n        init_kwargs.update(kwargs)\n        instance = super(Configurable, cls).__new__(impl)\n        # initialize vs __init__ chosen for compatibility with AsyncHTTPClient\n        # singleton magic.  If we get rid of that we can switch to __init__\n        # here too.\n        instance.initialize(*args, **init_kwargs)\n        return instance\n\n    @classmethod\n    def configurable_base(cls):\n        \"\"\"Returns the base class of a configurable hierarchy.\n\n        This will normally return the class in which it is defined.\n        (which is *not* necessarily the same as the cls classmethod parameter).\n        \"\"\"\n        raise NotImplementedError()\n\n    @classmethod\n    def configurable_default(cls):\n        \"\"\"Returns the implementation class to be used if none is configured.\"\"\"\n        raise NotImplementedError()\n\n    def initialize(self):\n        \"\"\"Initialize a `Configurable` subclass instance.\n\n        Configurable classes should use `initialize` instead of ``__init__``.\n\n        .. versionchanged:: 4.2\n           Now accepts positional arguments in addition to keyword arguments.\n        \"\"\"\n\n    @classmethod\n    def configure(cls, impl, **kwargs):\n        \"\"\"Sets the class to use when the base class is instantiated.\n\n        Keyword arguments will be saved and added to the arguments passed\n        to the constructor.  This can be used to set global defaults for\n        some parameters.\n        \"\"\"\n        base = cls.configurable_base()\n        if isinstance(impl, (unicode_type, bytes)):\n            impl = import_object(impl)\n        if impl is not None and not issubclass(impl, cls):\n            raise ValueError(\"Invalid subclass of %s\" % cls)\n        base.__impl_class = impl\n        base.__impl_kwargs = kwargs\n\n    @classmethod\n    def configured_class(cls):\n        \"\"\"Returns the currently configured class.\"\"\"\n        base = cls.configurable_base()\n        if cls.__impl_class is None:\n            base.__impl_class = cls.configurable_default()\n        return base.__impl_class\n\n    @classmethod\n    def _save_configuration(cls):\n        base = cls.configurable_base()\n        return (base.__impl_class, base.__impl_kwargs)\n\n    @classmethod\n    def _restore_configuration(cls, saved):\n        base = cls.configurable_base()\n        base.__impl_class = saved[0]\n        base.__impl_kwargs = saved[1]\n\n\nclass ArgReplacer(object):\n    \"\"\"Replaces one value in an ``args, kwargs`` pair.\n\n    Inspects the function signature to find an argument by name\n    whether it is passed by position or keyword.  For use in decorators\n    and similar wrappers.\n    \"\"\"\n    def __init__(self, func, name):\n        self.name = name\n        try:\n            self.arg_pos = self._getargnames(func).index(name)\n        except ValueError:\n            # Not a positional parameter\n            self.arg_pos = None\n\n    def _getargnames(self, func):\n        try:\n            return getargspec(func).args\n        except TypeError:\n            if hasattr(func, 'func_code'):\n                # Cython-generated code has all the attributes needed\n                # by inspect.getargspec, but the inspect module only\n                # works with ordinary functions. Inline the portion of\n                # getargspec that we need here. Note that for static\n                # functions the @cython.binding(True) decorator must\n                # be used (for methods it works out of the box).\n                code = func.func_code\n                return code.co_varnames[:code.co_argcount]\n            raise\n\n    def get_old_value(self, args, kwargs, default=None):\n        \"\"\"Returns the old value of the named argument without replacing it.\n\n        Returns ``default`` if the argument is not present.\n        \"\"\"\n        if self.arg_pos is not None and len(args) > self.arg_pos:\n            return args[self.arg_pos]\n        else:\n            return kwargs.get(self.name, default)\n\n    def replace(self, new_value, args, kwargs):\n        \"\"\"Replace the named argument in ``args, kwargs`` with ``new_value``.\n\n        Returns ``(old_value, args, kwargs)``.  The returned ``args`` and\n        ``kwargs`` objects may not be the same as the input objects, or\n        the input objects may be mutated.\n\n        If the named argument was not found, ``new_value`` will be added\n        to ``kwargs`` and None will be returned as ``old_value``.\n        \"\"\"\n        if self.arg_pos is not None and len(args) > self.arg_pos:\n            # The arg to replace is passed positionally\n            old_value = args[self.arg_pos]\n            args = list(args)  # *args is normally a tuple\n            args[self.arg_pos] = new_value\n        else:\n            # The arg to replace is either omitted or passed by keyword.\n            old_value = kwargs.get(self.name)\n            kwargs[self.name] = new_value\n        return old_value, args, kwargs\n\n\ndef timedelta_to_seconds(td):\n    \"\"\"Equivalent to td.total_seconds() (introduced in python 2.7).\"\"\"\n    return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 ** 6) / float(10 ** 6)\n\n\ndef _websocket_mask_python(mask, data):\n    \"\"\"Websocket masking function.\n\n    `mask` is a `bytes` object of length 4; `data` is a `bytes` object of any length.\n    Returns a `bytes` object of the same length as `data` with the mask applied\n    as specified in section 5.3 of RFC 6455.\n\n    This pure-python implementation may be replaced by an optimized version when available.\n    \"\"\"\n    mask = array.array(\"B\", mask)\n    unmasked = array.array(\"B\", data)\n    for i in xrange(len(data)):\n        unmasked[i] = unmasked[i] ^ mask[i % 4]\n    if hasattr(unmasked, 'tobytes'):\n        # tostring was deprecated in py32.  It hasn't been removed,\n        # but since we turn on deprecation warnings in our tests\n        # we need to use the right one.\n        return unmasked.tobytes()\n    else:\n        return unmasked.tostring()\n\nif (os.environ.get('TORNADO_NO_EXTENSION') or\n        os.environ.get('TORNADO_EXTENSION') == '0'):\n    # These environment variables exist to make it easier to do performance\n    # comparisons; they are not guaranteed to remain supported in the future.\n    _websocket_mask = _websocket_mask_python\nelse:\n    try:\n        from tornado.speedups import websocket_mask as _websocket_mask\n    except ImportError:\n        if os.environ.get('TORNADO_EXTENSION') == '1':\n            raise\n        _websocket_mask = _websocket_mask_python\n\n\ndef doctests():\n    import doctest\n    return doctest.DocTestSuite()\n",
            "new_file_content": "\"\"\"Miscellaneous utility functions and classes.\n\nThis module is used internally by Tornado.  It is not necessarily expected\nthat the functions and classes defined here will be useful to other\napplications, but they are documented here in case they are.\n\nThe one public-facing part of this module is the `Configurable` class\nand its `~Configurable.configure` method, which becomes a part of the\ninterface of its subclasses, including `.AsyncHTTPClient`, `.IOLoop`,\nand `.Resolver`.\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nimport array\nimport os\nimport re\nimport sys\nimport zlib\n\n\ntry:\n    xrange  # py2\nexcept NameError:\n    xrange = range  # py3\n\n# inspect.getargspec() raises DeprecationWarnings in Python 3.5.\n# The two functions have compatible interfaces for the parts we need.\ntry:\n    from inspect import getfullargspec as getargspec  # py3\nexcept ImportError:\n    from inspect import getargspec  # py2\n\n\nclass ObjectDict(dict):\n    \"\"\"Makes a dictionary behave like an object, with attribute-style access.\n    \"\"\"\n    def __getattr__(self, name):\n        try:\n            return self[name]\n        except KeyError:\n            raise AttributeError(name)\n\n    def __setattr__(self, name, value):\n        self[name] = value\n\n\nclass GzipDecompressor(object):\n    \"\"\"Streaming gzip decompressor.\n\n    The interface is like that of `zlib.decompressobj` (without some of the\n    optional arguments, but it understands gzip headers and checksums.\n    \"\"\"\n    def __init__(self):\n        # Magic parameter makes zlib module understand gzip header\n        # http://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib\n        # This works on cpython and pypy, but not jython.\n        self.decompressobj = zlib.decompressobj(16 + zlib.MAX_WBITS)\n\n    def decompress(self, value, max_length=None):\n        \"\"\"Decompress a chunk, returning newly-available data.\n\n        Some data may be buffered for later processing; `flush` must\n        be called when there is no more input data to ensure that\n        all data was processed.\n\n        If ``max_length`` is given, some input data may be left over\n        in ``unconsumed_tail``; you must retrieve this value and pass\n        it back to a future call to `decompress` if it is not empty.\n        \"\"\"\n        return self.decompressobj.decompress(value, max_length)\n\n    @property\n    def unconsumed_tail(self):\n        \"\"\"Returns the unconsumed portion left over\n        \"\"\"\n        return self.decompressobj.unconsumed_tail\n\n    def flush(self):\n        \"\"\"Return any remaining buffered data not yet returned by decompress.\n\n        Also checks for errors such as truncated input.\n        No other methods may be called on this object after `flush`.\n        \"\"\"\n        return self.decompressobj.flush()\n\n\nif not isinstance(b'', type('')):\n    unicode_type = str\n    basestring_type = str\nelse:\n    # These names don't exist in py3, so use noqa comments to disable\n    # warnings in flake8.\n    unicode_type = unicode  # noqa\n    basestring_type = basestring  # noqa\n\n\ndef import_object(name):\n    \"\"\"Imports an object by name.\n\n    import_object('x') is equivalent to 'import x'.\n    import_object('x.y.z') is equivalent to 'from x.y import z'.\n\n    >>> import tornado.escape\n    >>> import_object('tornado.escape') is tornado.escape\n    True\n    >>> import_object('tornado.escape.utf8') is tornado.escape.utf8\n    True\n    >>> import_object('tornado') is tornado\n    True\n    >>> import_object('tornado.missing_module')\n    Traceback (most recent call last):\n        ...\n    ImportError: No module named missing_module\n    \"\"\"\n    if isinstance(name, unicode_type) and str is not unicode_type:\n        # On python 2 a byte string is required.\n        name = name.encode('utf-8')\n    if name.count('.') == 0:\n        return __import__(name, None, None)\n\n    parts = name.split('.')\n    obj = __import__('.'.join(parts[:-1]), None, None, [parts[-1]], 0)\n    try:\n        return getattr(obj, parts[-1])\n    except AttributeError:\n        raise ImportError(\"No module named %s\" % parts[-1])\n\n\n# Deprecated alias that was used before we dropped py25 support.\n# Left here in case anyone outside Tornado is using it.\nbytes_type = bytes\n\nif sys.version_info > (3,):\n    exec(\"\"\"\ndef raise_exc_info(exc_info):\n    raise exc_info[1].with_traceback(exc_info[2])\n\ndef exec_in(code, glob, loc=None):\n    if isinstance(code, str):\n        code = compile(code, '<string>', 'exec', dont_inherit=True)\n    exec(code, glob, loc)\n\"\"\")\nelse:\n    exec(\"\"\"\ndef raise_exc_info(exc_info):\n    raise exc_info[0], exc_info[1], exc_info[2]\n\ndef exec_in(code, glob, loc=None):\n    if isinstance(code, basestring):\n        # exec(string) inherits the caller's future imports; compile\n        # the string first to prevent that.\n        code = compile(code, '<string>', 'exec', dont_inherit=True)\n    exec code in glob, loc\n\"\"\")\n\n\ndef errno_from_exception(e):\n    \"\"\"Provides the errno from an Exception object.\n\n    There are cases that the errno attribute was not set so we pull\n    the errno out of the args but if someone instantiates an Exception\n    without any args you will get a tuple error. So this function\n    abstracts all that behavior to give you a safe way to get the\n    errno.\n    \"\"\"\n\n    if hasattr(e, 'errno'):\n        return e.errno\n    elif e.args:\n        return e.args[0]\n    else:\n        return None\n\n\n_alphanum = frozenset(\n    \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\")\n\ndef _re_unescape_replacement(match):\n    group = match.group(1)\n    if group[0] in _alphanum:\n        raise ValueError(\"cannot unescape '\\\\\\\\%s'\" % group[0])\n    return group\n\n_re_unescape_pattern = re.compile(r'\\\\(.)', re.DOTALL)\n\ndef re_unescape(s):\n    '''\n    unescape a string escaped by ``re.escape()``\n    '''\n    return _re_unescape_pattern.sub(_re_unescape_replacement, s)\n\n\nclass Configurable(object):\n    \"\"\"Base class for configurable interfaces.\n\n    A configurable interface is an (abstract) class whose constructor\n    acts as a factory function for one of its implementation subclasses.\n    The implementation subclass as well as optional keyword arguments to\n    its initializer can be set globally at runtime with `configure`.\n\n    By using the constructor as the factory method, the interface\n    looks like a normal class, `isinstance` works as usual, etc.  This\n    pattern is most useful when the choice of implementation is likely\n    to be a global decision (e.g. when `~select.epoll` is available,\n    always use it instead of `~select.select`), or when a\n    previously-monolithic class has been split into specialized\n    subclasses.\n\n    Configurable subclasses must define the class methods\n    `configurable_base` and `configurable_default`, and use the instance\n    method `initialize` instead of ``__init__``.\n    \"\"\"\n    __impl_class = None\n    __impl_kwargs = None\n\n    def __new__(cls, *args, **kwargs):\n        base = cls.configurable_base()\n        init_kwargs = {}\n        if cls is base:\n            impl = cls.configured_class()\n            if base.__impl_kwargs:\n                init_kwargs.update(base.__impl_kwargs)\n        else:\n            impl = cls\n        init_kwargs.update(kwargs)\n        instance = super(Configurable, cls).__new__(impl)\n        # initialize vs __init__ chosen for compatibility with AsyncHTTPClient\n        # singleton magic.  If we get rid of that we can switch to __init__\n        # here too.\n        instance.initialize(*args, **init_kwargs)\n        return instance\n\n    @classmethod\n    def configurable_base(cls):\n        \"\"\"Returns the base class of a configurable hierarchy.\n\n        This will normally return the class in which it is defined.\n        (which is *not* necessarily the same as the cls classmethod parameter).\n        \"\"\"\n        raise NotImplementedError()\n\n    @classmethod\n    def configurable_default(cls):\n        \"\"\"Returns the implementation class to be used if none is configured.\"\"\"\n        raise NotImplementedError()\n\n    def initialize(self):\n        \"\"\"Initialize a `Configurable` subclass instance.\n\n        Configurable classes should use `initialize` instead of ``__init__``.\n\n        .. versionchanged:: 4.2\n           Now accepts positional arguments in addition to keyword arguments.\n        \"\"\"\n\n    @classmethod\n    def configure(cls, impl, **kwargs):\n        \"\"\"Sets the class to use when the base class is instantiated.\n\n        Keyword arguments will be saved and added to the arguments passed\n        to the constructor.  This can be used to set global defaults for\n        some parameters.\n        \"\"\"\n        base = cls.configurable_base()\n        if isinstance(impl, (unicode_type, bytes)):\n            impl = import_object(impl)\n        if impl is not None and not issubclass(impl, cls):\n            raise ValueError(\"Invalid subclass of %s\" % cls)\n        base.__impl_class = impl\n        base.__impl_kwargs = kwargs\n\n    @classmethod\n    def configured_class(cls):\n        \"\"\"Returns the currently configured class.\"\"\"\n        base = cls.configurable_base()\n        if cls.__impl_class is None:\n            base.__impl_class = cls.configurable_default()\n        return base.__impl_class\n\n    @classmethod\n    def _save_configuration(cls):\n        base = cls.configurable_base()\n        return (base.__impl_class, base.__impl_kwargs)\n\n    @classmethod\n    def _restore_configuration(cls, saved):\n        base = cls.configurable_base()\n        base.__impl_class = saved[0]\n        base.__impl_kwargs = saved[1]\n\n\nclass ArgReplacer(object):\n    \"\"\"Replaces one value in an ``args, kwargs`` pair.\n\n    Inspects the function signature to find an argument by name\n    whether it is passed by position or keyword.  For use in decorators\n    and similar wrappers.\n    \"\"\"\n    def __init__(self, func, name):\n        self.name = name\n        try:\n            self.arg_pos = self._getargnames(func).index(name)\n        except ValueError:\n            # Not a positional parameter\n            self.arg_pos = None\n\n    def _getargnames(self, func):\n        try:\n            return getargspec(func).args\n        except TypeError:\n            if hasattr(func, 'func_code'):\n                # Cython-generated code has all the attributes needed\n                # by inspect.getargspec, but the inspect module only\n                # works with ordinary functions. Inline the portion of\n                # getargspec that we need here. Note that for static\n                # functions the @cython.binding(True) decorator must\n                # be used (for methods it works out of the box).\n                code = func.func_code\n                return code.co_varnames[:code.co_argcount]\n            raise\n\n    def get_old_value(self, args, kwargs, default=None):\n        \"\"\"Returns the old value of the named argument without replacing it.\n\n        Returns ``default`` if the argument is not present.\n        \"\"\"\n        if self.arg_pos is not None and len(args) > self.arg_pos:\n            return args[self.arg_pos]\n        else:\n            return kwargs.get(self.name, default)\n\n    def replace(self, new_value, args, kwargs):\n        \"\"\"Replace the named argument in ``args, kwargs`` with ``new_value``.\n\n        Returns ``(old_value, args, kwargs)``.  The returned ``args`` and\n        ``kwargs`` objects may not be the same as the input objects, or\n        the input objects may be mutated.\n\n        If the named argument was not found, ``new_value`` will be added\n        to ``kwargs`` and None will be returned as ``old_value``.\n        \"\"\"\n        if self.arg_pos is not None and len(args) > self.arg_pos:\n            # The arg to replace is passed positionally\n            old_value = args[self.arg_pos]\n            args = list(args)  # *args is normally a tuple\n            args[self.arg_pos] = new_value\n        else:\n            # The arg to replace is either omitted or passed by keyword.\n            old_value = kwargs.get(self.name)\n            kwargs[self.name] = new_value\n        return old_value, args, kwargs\n\n\ndef timedelta_to_seconds(td):\n    \"\"\"Equivalent to td.total_seconds() (introduced in python 2.7).\"\"\"\n    return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 ** 6) / float(10 ** 6)\n\n\ndef _websocket_mask_python(mask, data):\n    \"\"\"Websocket masking function.\n\n    `mask` is a `bytes` object of length 4; `data` is a `bytes` object of any length.\n    Returns a `bytes` object of the same length as `data` with the mask applied\n    as specified in section 5.3 of RFC 6455.\n\n    This pure-python implementation may be replaced by an optimized version when available.\n    \"\"\"\n    mask = array.array(\"B\", mask)\n    unmasked = array.array(\"B\", data)\n    for i in xrange(len(data)):\n        unmasked[i] = unmasked[i] ^ mask[i % 4]\n    if hasattr(unmasked, 'tobytes'):\n        # tostring was deprecated in py32.  It hasn't been removed,\n        # but since we turn on deprecation warnings in our tests\n        # we need to use the right one.\n        return unmasked.tobytes()\n    else:\n        return unmasked.tostring()\n\nif (os.environ.get('TORNADO_NO_EXTENSION') or\n        os.environ.get('TORNADO_EXTENSION') == '0'):\n    # These environment variables exist to make it easier to do performance\n    # comparisons; they are not guaranteed to remain supported in the future.\n    _websocket_mask = _websocket_mask_python\nelse:\n    try:\n        from tornado.speedups import websocket_mask as _websocket_mask\n    except ImportError:\n        if os.environ.get('TORNADO_EXTENSION') == '1':\n            raise\n        _websocket_mask = _websocket_mask_python\n\n\ndef doctests():\n    import doctest\n    return doctest.DocTestSuite()\n",
            "header": {
                "file": {
                    "path": "tornado/util.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "e74be97c",
                "new_commit_hash": "a0401c14",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tornado/util.py"
            },
            "plus_file": {
                "path": "b/tornado/util.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 173,
                            "length": 20
                        },
                        "new_range": {
                            "start": 173,
                            "length": 22
                        },
                        "section": "def errno_from_exception(e):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        return None",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "_re_unescape_split_pattern = re.compile(r'(\\\\[^0])')",
                                "type": "deleted"
                            },
                            {
                                "content": "# re.escape('\\x00') is a special case",
                                "type": "deleted"
                            },
                            {
                                "content": "_alphanum = frozenset(",
                                "type": "added"
                            },
                            {
                                "content": "    \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\")",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "def _re_unescape_replacement(match):",
                                "type": "added"
                            },
                            {
                                "content": "    group = match.group(1)",
                                "type": "added"
                            },
                            {
                                "content": "    if group[0] in _alphanum:",
                                "type": "added"
                            },
                            {
                                "content": "        raise ValueError(\"cannot unescape '\\\\\\\\%s'\" % group[0])",
                                "type": "added"
                            },
                            {
                                "content": "    return group",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "_re_unescape_pattern = re.compile(r'\\\\(.)', re.DOTALL)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "def re_unescape(s):",
                                "type": "context"
                            },
                            {
                                "content": "    '''",
                                "type": "context"
                            },
                            {
                                "content": "    unescape a string escaped by ``re.escape()``",
                                "type": "context"
                            },
                            {
                                "content": "    '''",
                                "type": "context"
                            },
                            {
                                "content": "    parts = []",
                                "type": "deleted"
                            },
                            {
                                "content": "    for i, splited in enumerate(_re_unescape_split_pattern.split(s)):",
                                "type": "deleted"
                            },
                            {
                                "content": "        if i % 2:",
                                "type": "deleted"
                            },
                            {
                                "content": "            parts.append(splited[1])",
                                "type": "deleted"
                            },
                            {
                                "content": "        else:",
                                "type": "deleted"
                            },
                            {
                                "content": "            parts.append(splited.replace(r'\\000', '\\000'))",
                                "type": "deleted"
                            },
                            {
                                "content": "    return ''.join(parts)",
                                "type": "deleted"
                            },
                            {
                                "content": "    return _re_unescape_pattern.sub(_re_unescape_replacement, s)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "class Configurable(object):",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/util.py",
                            "type": "function",
                            "name": "re_unescape",
                            "content": "def re_unescape(s):\n    '''\n    unescape a string escaped by ``re.escape()``\n    '''\n    parts = []\n    for i, splited in enumerate(_re_unescape_split_pattern.split(s)):\n        if i % 2:\n            parts.append(splited[1])\n        else:\n            parts.append(splited.replace(r'\\000', '\\000'))\n    return ''.join(parts)",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 179,
                            "end_lineno": 189,
                            "parent": null
                        }
                    ],
                    "added_entities": [
                        {
                            "file_name": "tornado/util.py",
                            "type": "statement",
                            "name": "",
                            "content": "_re_unescape_pattern = re.compile(r'\\\\(.)', re.DOTALL)",
                            "ast_type_str": "Assign",
                            "start_lineno": 185,
                            "end_lineno": 185,
                            "parent": null
                        },
                        {
                            "file_name": "tornado/util.py",
                            "type": "statement",
                            "name": "",
                            "content": "_alphanum = frozenset(\n    \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\")",
                            "ast_type_str": "Assign",
                            "start_lineno": 176,
                            "end_lineno": 177,
                            "parent": null
                        },
                        {
                            "file_name": "tornado/util.py",
                            "type": "function",
                            "name": "_re_unescape_replacement",
                            "content": "def _re_unescape_replacement(match):\n    group = match.group(1)\n    if group[0] in _alphanum:\n        raise ValueError(\"cannot unescape '\\\\\\\\%s'\" % group[0])\n    return group",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 179,
                            "end_lineno": 183,
                            "parent": null
                        }
                    ],
                    "deleted_entities": [
                        {
                            "file_name": "tornado/util.py",
                            "type": "statement",
                            "name": "",
                            "content": "_re_unescape_split_pattern = re.compile(r'(\\\\[^0])')",
                            "ast_type_str": "Assign",
                            "start_lineno": 176,
                            "end_lineno": 176,
                            "parent": null
                        }
                    ]
                }
            ]
        },
        {
            "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.. testcode::\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.current().start()\n\n.. testoutput::\n   :hide:\n\n\nSee the :doc:`guide` for additional information.\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\"\"\"\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\nfrom io import BytesIO\n\nfrom tornado.concurrent import Future\nfrom tornado import escape\nfrom tornado import gen\nfrom tornado import httputil\nfrom tornado import iostream\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 (import_object, ObjectDict, raise_exc_info,\n                          unicode_type, _websocket_mask, re_unescape)\nfrom tornado.httputil import split_host_and_port\n\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\nMIN_SUPPORTED_SIGNED_VALUE_VERSION = 1\n\"\"\"The oldest signed value version supported by this version of Tornado.\n\nSigned values older than this version cannot be decoded.\n\n.. versionadded:: 3.2.1\n\"\"\"\n\nMAX_SUPPORTED_SIGNED_VALUE_VERSION = 2\n\"\"\"The newest signed value version supported by this version of Tornado.\n\nSigned values newer than this version cannot be decoded.\n\n.. versionadded:: 3.2.1\n\"\"\"\n\nDEFAULT_SIGNED_VALUE_VERSION = 2\n\"\"\"The signed value version produced by `.RequestHandler.create_signed_value`.\n\nMay be overridden by passing a ``version`` keyword argument.\n\n.. versionadded:: 3.2.1\n\"\"\"\n\nDEFAULT_SIGNED_VALUE_MIN_VERSION = 1\n\"\"\"The oldest signed value accepted by `.RequestHandler.get_secure_cookie`.\n\nMay be overridden by passing a ``min_version`` keyword argument.\n\n.. versionadded:: 3.2.1\n\"\"\"\n\n\nclass RequestHandler(object):\n    \"\"\"Base class for HTTP request handlers.\n\n    Subclasses must define at least one of the methods defined in the\n    \"Entry points\" section below.\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._prepared_future = None\n        self.path_args = None\n        self.path_kwargs = None\n        self.ui = ObjectDict((n, self._ui_method(m)) for n, m in\n                             application.ui_methods.items())\n        # UIModules are available as both `modules` and `_tt_modules` in the\n        # template namespace.  Historically only `modules` was available\n        # but could be clobbered by user additions to the namespace.\n        # The template {% module %} directive looks in `_tt_modules` to avoid\n        # possible conflicts.\n        self.ui[\"_tt_modules\"] = _UIModuleNamespace(self,\n                                                    application.ui_modules)\n        self.ui[\"modules\"] = self.ui[\"_tt_modules\"]\n        self.clear()\n        self.request.connection.set_close_callback(self.on_connection_close)\n        self.initialize(**kwargs)\n\n    def initialize(self):\n        \"\"\"Hook for subclass initialization. Called for each request.\n\n        A dictionary passed as the third argument of a url spec will be\n        supplied as keyword arguments to initialize().\n\n        Example::\n\n            class ProfileHandler(RequestHandler):\n                def initialize(self, database):\n                    self.database = database\n\n                def get(self, username):\n                    ...\n\n            app = Application([\n                (r'/user/(.*)', ProfileHandler, dict(database=database)),\n                ])\n        \"\"\"\n        pass\n\n    @property\n    def settings(self):\n        \"\"\"An alias for `self.application.settings <Application.settings>`.\"\"\"\n        return self.application.settings\n\n    def head(self, *args, **kwargs):\n        raise HTTPError(405)\n\n    def get(self, *args, **kwargs):\n        raise HTTPError(405)\n\n    def post(self, *args, **kwargs):\n        raise HTTPError(405)\n\n    def delete(self, *args, **kwargs):\n        raise HTTPError(405)\n\n    def patch(self, *args, **kwargs):\n        raise HTTPError(405)\n\n    def put(self, *args, **kwargs):\n        raise HTTPError(405)\n\n    def options(self, *args, **kwargs):\n        raise HTTPError(405)\n\n    def prepare(self):\n        \"\"\"Called at the beginning of a request before  `get`/`post`/etc.\n\n        Override this method to perform common initialization regardless\n        of the request method.\n\n        Asynchronous support: Decorate this method with `.gen.coroutine`\n        or `.return_future` to make it asynchronous (the\n        `asynchronous` decorator cannot be used on `prepare`).\n        If this method returns a `.Future` execution will not proceed\n        until the `.Future` is done.\n\n        .. versionadded:: 3.1\n           Asynchronous support.\n        \"\"\"\n        pass\n\n    def on_finish(self):\n        \"\"\"Called after the end of a request.\n\n        Override this method to perform cleanup, logging, etc.\n        This method is a counterpart to `prepare`.  ``on_finish`` may\n        not produce any output, as it is called after the response\n        has been sent to the client.\n        \"\"\"\n        pass\n\n    def on_connection_close(self):\n        \"\"\"Called in async handlers if the client closed the connection.\n\n        Override this to clean up resources associated with\n        long-lived connections.  Note that this method is called only if\n        the connection was closed during asynchronous processing; if you\n        need to do cleanup after every request override `on_finish`\n        instead.\n\n        Proxies may keep a connection open for a time (perhaps\n        indefinitely) after the client has gone away, so this method\n        may not be called promptly after the end user closes their\n        connection.\n        \"\"\"\n        if _has_stream_request_body(self.__class__):\n            if not self.request.body.done():\n                self.request.body.set_exception(iostream.StreamClosedError())\n                self.request.body.exception()\n\n    def clear(self):\n        \"\"\"Resets all headers and content for this response.\"\"\"\n        self._headers = httputil.HTTPHeaders({\n            \"Server\": \"TornadoServer/%s\" % tornado.version,\n            \"Content-Type\": \"text/html; charset=UTF-8\",\n            \"Date\": httputil.format_timestamp(time.time()),\n        })\n        self.set_default_headers()\n        self._write_buffer = []\n        self._status_code = 200\n        self._reason = httputil.responses[200]\n\n    def set_default_headers(self):\n        \"\"\"Override this to set HTTP headers at the beginning of the request.\n\n        For example, this is the place to set a custom ``Server`` header.\n        Note that setting such headers in the normal flow of request\n        processing may not do what you want, since headers may be reset\n        during error handling.\n        \"\"\"\n        pass\n\n    def set_status(self, status_code, reason=None):\n        \"\"\"Sets the status code for our response.\n\n        :arg int status_code: Response status code. If ``reason`` is ``None``,\n            it must be present in `httplib.responses <http.client.responses>`.\n        :arg string reason: Human-readable reason phrase describing the status\n            code. If ``None``, it will be filled in from\n            `httplib.responses <http.client.responses>`.\n        \"\"\"\n        self._status_code = status_code\n        if reason is not None:\n            self._reason = escape.native_str(reason)\n        else:\n            try:\n                self._reason = httputil.responses[status_code]\n            except KeyError:\n                raise ValueError(\"unknown status code %d\", status_code)\n\n    def get_status(self):\n        \"\"\"Returns the status code for our response.\"\"\"\n        return self._status_code\n\n    def set_header(self, name, value):\n        \"\"\"Sets the given response header name and value.\n\n        If a datetime is given, we automatically format it according to the\n        HTTP specification. If the value is not a string, we convert it to\n        a string. All header values are then encoded as UTF-8.\n        \"\"\"\n        self._headers[name] = self._convert_header_value(value)\n\n    def add_header(self, name, value):\n        \"\"\"Adds the given response header and value.\n\n        Unlike `set_header`, `add_header` may be called multiple times\n        to return multiple values for the same header.\n        \"\"\"\n        self._headers.add(name, self._convert_header_value(value))\n\n    def clear_header(self, name):\n        \"\"\"Clears an outgoing header, undoing a previous `set_header` call.\n\n        Note that this method does not apply to multi-valued headers\n        set by `add_header`.\n        \"\"\"\n        if name in self._headers:\n            del self._headers[name]\n\n    _INVALID_HEADER_CHAR_RE = re.compile(br\"[\\x00-\\x1f]\")\n\n    def _convert_header_value(self, value):\n        if isinstance(value, bytes):\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.\n        if RequestHandler._INVALID_HEADER_CHAR_RE.search(value):\n            raise ValueError(\"Unsafe header value %r\", value)\n        return value\n\n    _ARG_DEFAULT = []\n\n    def get_argument(self, name, default=_ARG_DEFAULT, strip=True):\n        \"\"\"Returns the value of the argument with the given name.\n\n        If default is not provided, the argument is considered to be\n        required, and we raise a `MissingArgumentError` if it is missing.\n\n        If the argument appears in the url more than once, we return the\n        last value.\n\n        The returned value is always unicode.\n        \"\"\"\n        return self._get_argument(name, default, self.request.arguments, strip)\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        # Make sure `get_arguments` isn't accidentally being called with a\n        # positional argument that's assumed to be a default (like in\n        # `get_argument`.)\n        assert isinstance(strip, bool)\n\n        return self._get_arguments(name, self.request.arguments, strip)\n\n    def get_body_argument(self, name, default=_ARG_DEFAULT, strip=True):\n        \"\"\"Returns the value of the argument with the given name\n        from the request body.\n\n        If default is not provided, the argument is considered to be\n        required, and we raise a `MissingArgumentError` if it is missing.\n\n        If the argument appears in the url more than once, we return the\n        last value.\n\n        The returned value is always unicode.\n\n        .. versionadded:: 3.2\n        \"\"\"\n        return self._get_argument(name, default, self.request.body_arguments,\n                                  strip)\n\n    def get_body_arguments(self, name, strip=True):\n        \"\"\"Returns a list of the body 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        .. versionadded:: 3.2\n        \"\"\"\n        return self._get_arguments(name, self.request.body_arguments, strip)\n\n    def get_query_argument(self, name, default=_ARG_DEFAULT, strip=True):\n        \"\"\"Returns the value of the argument with the given name\n        from the request query string.\n\n        If default is not provided, the argument is considered to be\n        required, and we raise a `MissingArgumentError` if it is missing.\n\n        If the argument appears in the url more than once, we return the\n        last value.\n\n        The returned value is always unicode.\n\n        .. versionadded:: 3.2\n        \"\"\"\n        return self._get_argument(name, default,\n                                  self.request.query_arguments, strip)\n\n    def get_query_arguments(self, name, strip=True):\n        \"\"\"Returns a list of the query 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        .. versionadded:: 3.2\n        \"\"\"\n        return self._get_arguments(name, self.request.query_arguments, strip)\n\n    def _get_argument(self, name, default, source, strip=True):\n        args = self._get_arguments(name, source, strip=strip)\n        if not args:\n            if default is self._ARG_DEFAULT:\n                raise MissingArgumentError(name)\n            return default\n        return args[-1]\n\n    def _get_arguments(self, name, source, strip=True):\n        values = []\n        for v in source.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        try:\n            return _unicode(value)\n        except UnicodeDecodeError:\n            raise HTTPError(400, \"Invalid unicode in %s: %r\" %\n                            (name or \"url\", value[:40]))\n\n    @property\n    def cookies(self):\n        \"\"\"An alias for\n        `self.request.cookies <.httputil.HTTPServerRequest.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\n            # skip falsy values for httponly and secure flags because\n            # SimpleCookie sets them regardless\n            if k in ['httponly', 'secure'] and not v:\n                continue\n\n            morsel[k] = v\n\n    def clear_cookie(self, name, path=\"/\", domain=None):\n        \"\"\"Deletes the cookie with the given name.\n\n        Due to limitations of the cookie protocol, you must pass the same\n        path and domain to clear a cookie as were used when that cookie\n        was set (but there is no way to find out on the server side\n        which values were used for a given cookie).\n        \"\"\"\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, path=\"/\", domain=None):\n        \"\"\"Deletes all the cookies the user sent with this request.\n\n        See `clear_cookie` for more information on the path and domain\n        parameters.\n\n        .. versionchanged:: 3.2\n\n           Added the ``path`` and ``domain`` parameters.\n        \"\"\"\n        for name in self.request.cookies:\n            self.clear_cookie(name, path=path, domain=domain)\n\n    def set_secure_cookie(self, name, value, expires_days=30, version=None,\n                          **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        .. versionchanged:: 3.2.1\n\n           Added the ``version`` argument.  Introduced cookie version 2\n           and made it the default.\n        \"\"\"\n        self.set_cookie(name, self.create_signed_value(name, value,\n                                                       version=version),\n                        expires_days=expires_days, **kwargs)\n\n    def create_signed_value(self, name, value, version=None):\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        .. versionchanged:: 3.2.1\n\n           Added the ``version`` argument.  Introduced cookie version 2\n           and made it the default.\n        \"\"\"\n        self.require_setting(\"cookie_secret\", \"secure cookies\")\n        secret = self.application.settings[\"cookie_secret\"]\n        key_version = None\n        if isinstance(secret, dict):\n            if self.application.settings.get(\"key_version\") is None:\n                raise Exception(\"key_version setting must be used for secret_key dicts\")\n            key_version = self.application.settings[\"key_version\"]\n\n        return create_signed_value(secret, name, value, version=version,\n                                   key_version=key_version)\n\n    def get_secure_cookie(self, name, value=None, max_age_days=31,\n                          min_version=None):\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        .. versionchanged:: 3.2.1\n\n           Added the ``min_version`` argument.  Introduced cookie version 2;\n           both versions 1 and 2 are accepted by default.\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                                   min_version=min_version)\n\n    def get_secure_cookie_key_version(self, name, value=None):\n        \"\"\"Returns the signing key version of the secure cookie.\n\n        The version is returned as int.\n        \"\"\"\n        self.require_setting(\"cookie_secret\", \"secure cookies\")\n        if value is None:\n            value = self.get_cookie(name)\n        return get_signature_key_version(value)\n\n    def redirect(self, url, permanent=False, status=None):\n        \"\"\"Sends a redirect to the given (optionally relative) URL.\n\n        If the ``status`` argument is specified, that value is used as the\n        HTTP status code; otherwise either 301 (permanent) or 302\n        (temporary) is chosen based on the ``permanent`` argument.\n        The default is 302 (temporary).\n        \"\"\"\n        if self._headers_written:\n            raise Exception(\"Cannot redirect after headers have been written\")\n        if status is None:\n            status = 301 if permanent else 302\n        else:\n            assert isinstance(status, int) and 300 <= status <= 399\n        self.set_status(status)\n        self.set_header(\"Location\", utf8(url))\n        self.finish()\n\n    def write(self, chunk):\n        \"\"\"Writes the given chunk to the output buffer.\n\n        To write the output to the network, use the flush() method below.\n\n        If the given chunk is a dictionary, we write it as JSON and set\n        the Content-Type of the response to be ``application/json``.\n        (if you want to send JSON as a different ``Content-Type``, call\n        set_header *after* calling write()).\n\n        Note that lists are not converted to JSON because of a potential\n        cross-site security vulnerability.  All JSON output should be\n        wrapped in a dictionary.  More details at\n        http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ and\n        https://github.com/facebook/tornado/issues/1009\n        \"\"\"\n        if self._finished:\n            raise RuntimeError(\"Cannot write() after finish()\")\n        if not isinstance(chunk, (bytes, unicode_type, dict)):\n            message = \"write() only accepts bytes, unicode, and dict objects\"\n            if isinstance(chunk, list):\n                message += \". Lists not accepted for security reasons; see http://www.tornadoweb.org/en/stable/web.html#tornado.web.RequestHandler.write\"\n            raise TypeError(message)\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)):\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)):\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            pgettext=self.locale.pgettext,\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`` and ``template_whitespace`` application\n        settings.  If a ``template_loader`` application setting is\n        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        if \"template_whitespace\" in settings:\n            kwargs[\"whitespace\"] = settings[\"template_whitespace\"]\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        .. versionchanged:: 4.0\n           Now returns a `.Future` if no callback is given.\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,\n                        chunk, include_footers)\n            # Ignore the chunk and only write the headers for HEAD requests\n            if self.request.method == \"HEAD\":\n                chunk = None\n\n            # Finalize the cookie headers (which have been stored in a side\n            # object so an outgoing cookie could be overwritten before it\n            # is sent).\n            if hasattr(self, \"_new_cookie\"):\n                for cookie in self._new_cookie.values():\n                    self.add_header(\"Set-Cookie\", cookie.OutputString(None))\n\n            start_line = httputil.ResponseStartLine('',\n                                                    self._status_code,\n                                                    self._reason)\n            return self.request.connection.write_headers(\n                start_line, self._headers, chunk, callback=callback)\n        else:\n            for transform in self._transforms:\n                chunk = transform.transform_chunk(chunk, include_footers)\n            # Ignore the chunk and only write the headers for HEAD requests\n            if self.request.method != \"HEAD\":\n                return self.request.connection.write(chunk, callback=callback)\n            else:\n                future = Future()\n                future.set_result(None)\n                return future\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\")\n\n        if chunk is not None:\n            self.write(chunk)\n\n        # Automatically support ETags and add the Content-Length header if\n        # we have not flushed any content yet.\n        if not self._headers_written:\n            if (self._status_code == 200 and\n                self.request.method in (\"GET\", \"HEAD\") and\n                    \"Etag\" not in self._headers):\n                self.set_etag_header()\n                if self.check_etag_header():\n                    self._write_buffer = []\n                    self.set_status(304)\n            if self._status_code == 304:\n                assert not self._write_buffer, \"Cannot send body with 304\"\n                self._clear_headers_for_304()\n            elif \"Content-Length\" not in self._headers:\n                content_length = sum(len(part) for part in self._write_buffer)\n                self.set_header(\"Content-Length\", content_length)\n\n        if hasattr(self.request, \"connection\"):\n            # Now that the request is finished, clear the callback we\n            # set on the HTTPConnection (which would otherwise prevent the\n            # garbage collection of the RequestHandler when there\n            # are keepalive connections)\n            self.request.connection.set_close_callback(None)\n\n        self.flush(include_footers=True)\n        self.request.finish()\n        self._log()\n        self._finished = True\n        self.on_finish()\n        # Break up a reference cycle between this handler and the\n        # _ui_module closures to allow for faster GC on CPython.\n        self.ui = None\n\n    def send_error(self, status_code=500, **kwargs):\n        \"\"\"Sends the given HTTP error code to the browser.\n\n        If `flush()` has already been called, it is not possible to send\n        an error, so this method will simply terminate the response.\n        If output has been written but not yet flushed, it will be discarded\n        and replaced with the error page.\n\n        Override `write_error()` to customize the error page that is returned.\n        Additional keyword arguments are passed through to `write_error`.\n        \"\"\"\n        if self._headers_written:\n            gen_log.error(\"Cannot send error response after headers written\")\n            if not self._finished:\n                # If we get an error between writing headers and finishing,\n                # we are unlikely to be able to finish due to a\n                # Content-Length mismatch. Try anyway to release the\n                # socket.\n                try:\n                    self.finish()\n                except Exception:\n                    gen_log.error(\"Failed to flush partial response\",\n                                  exc_info=True)\n            return\n        self.clear()\n\n        reason = kwargs.get('reason')\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        if self.settings.get(\"serve_traceback\") 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 locale 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        .. versionchanged: 4.1\n           Added a property setter.\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    @locale.setter\n    def locale(self, value):\n        self._locale = value\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 set in one of two ways:\n\n        * A subclass may override `get_current_user()`, which will be called\n          automatically the first time ``self.current_user`` is accessed.\n          `get_current_user()` will only be called once per request,\n          and is cached for future access::\n\n              def get_current_user(self):\n                  user_cookie = self.get_secure_cookie(\"user\")\n                      if user_cookie:\n                          return json.loads(user_cookie)\n                  return None\n\n        * It may be set as a normal variable, typically from an overridden\n          `prepare()`::\n\n              @gen.coroutine\n              def prepare(self):\n                  user_id_cookie = self.get_secure_cookie(\"user_id\")\n                  if user_id_cookie:\n                      self.current_user = yield load_user(user_id_cookie)\n\n        Note that `prepare()` may be a coroutine while `get_current_user()`\n        may not, so the latter form is necessary if loading the user requires\n        asynchronous operations.\n\n        The user object may any type of the application's choosing.\n        \"\"\"\n        if not hasattr(self, \"_current_user\"):\n            self._current_user = self.get_current_user()\n        return self._current_user\n\n    @current_user.setter\n    def current_user(self, value):\n        self._current_user = value\n\n    def get_current_user(self):\n        \"\"\"Override to determine the current user from, e.g., a cookie.\n\n        This method may not be a coroutine.\n        \"\"\"\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        .. versionchanged:: 3.2.2\n           The xsrf token will now be have a random mask applied in every\n           request, which makes it safe to include the token in pages\n           that are compressed.  See http://breachattack.com for more\n           information on the issue fixed by this change.  Old (version 1)\n           cookies will be converted to version 2 when this method is called\n           unless the ``xsrf_cookie_version`` `Application` setting is\n           set to 1.\n\n        .. versionchanged:: 4.3\n           The ``xsrf_cookie_kwargs`` `Application` setting may be\n           used to supply additional cookie options (which will be\n           passed directly to `set_cookie`). For example,\n           ``xsrf_cookie_kwargs=dict(httponly=True, secure=True)``\n           will set the ``secure`` and ``httponly`` flags on the\n           ``_xsrf`` cookie.\n        \"\"\"\n        if not hasattr(self, \"_xsrf_token\"):\n            version, token, timestamp = self._get_raw_xsrf_token()\n            output_version = self.settings.get(\"xsrf_cookie_version\", 2)\n            cookie_kwargs = self.settings.get(\"xsrf_cookie_kwargs\", {})\n            if output_version == 1:\n                self._xsrf_token = binascii.b2a_hex(token)\n            elif output_version == 2:\n                mask = os.urandom(4)\n                self._xsrf_token = b\"|\".join([\n                    b\"2\",\n                    binascii.b2a_hex(mask),\n                    binascii.b2a_hex(_websocket_mask(mask, token)),\n                    utf8(str(int(timestamp)))])\n            else:\n                raise ValueError(\"unknown xsrf cookie version %d\",\n                                 output_version)\n            if version is None:\n                expires_days = 30 if self.current_user else None\n                self.set_cookie(\"_xsrf\", self._xsrf_token,\n                                expires_days=expires_days,\n                                **cookie_kwargs)\n        return self._xsrf_token\n\n    def _get_raw_xsrf_token(self):\n        \"\"\"Read or generate the xsrf token in its raw form.\n\n        The raw_xsrf_token is a tuple containing:\n\n        * version: the version of the cookie from which this token was read,\n          or None if we generated a new token in this request.\n        * token: the raw token data; random (non-ascii) bytes.\n        * timestamp: the time this token was generated (will not be accurate\n          for version 1 cookies)\n        \"\"\"\n        if not hasattr(self, '_raw_xsrf_token'):\n            cookie = self.get_cookie(\"_xsrf\")\n            if cookie:\n                version, token, timestamp = self._decode_xsrf_token(cookie)\n            else:\n                version, token, timestamp = None, None, None\n            if token is None:\n                version = None\n                token = os.urandom(16)\n                timestamp = time.time()\n            self._raw_xsrf_token = (version, token, timestamp)\n        return self._raw_xsrf_token\n\n    def _decode_xsrf_token(self, cookie):\n        \"\"\"Convert a cookie string into a the tuple form returned by\n        _get_raw_xsrf_token.\n        \"\"\"\n\n        try:\n            m = _signed_value_version_re.match(utf8(cookie))\n\n            if m:\n                version = int(m.group(1))\n                if version == 2:\n                    _, mask, masked_token, timestamp = cookie.split(\"|\")\n\n                    mask = binascii.a2b_hex(utf8(mask))\n                    token = _websocket_mask(\n                        mask, binascii.a2b_hex(utf8(masked_token)))\n                    timestamp = int(timestamp)\n                    return version, token, timestamp\n                else:\n                    # Treat unknown versions as not present instead of failing.\n                    raise Exception(\"Unknown xsrf cookie version\")\n            else:\n                version = 1\n                try:\n                    token = binascii.a2b_hex(utf8(cookie))\n                except (binascii.Error, TypeError):\n                    token = utf8(cookie)\n                # We don't have a usable timestamp in older versions.\n                timestamp = int(time.time())\n                return (version, token, timestamp)\n        except Exception:\n            # Catch exceptions and return nothing instead of failing.\n            gen_log.debug(\"Uncaught exception in _decode_xsrf_token\",\n                          exc_info=True)\n            return None, None, None\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        .. versionchanged:: 3.2.2\n           Added support for cookie version 2.  Both versions 1 and 2 are\n           supported.\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        _, token, _ = self._decode_xsrf_token(token)\n        _, expected_token, _ = self._get_raw_xsrf_token()\n        if not _time_independent_equals(utf8(token), utf8(expected_token)):\n            raise HTTPError(403, \"XSRF cookie does not match POST argument\")\n\n    def xsrf_form_html(self):\n        \"\"\"An HTML ``<input/>`` element to be included with all POST forms.\n\n        It defines the ``_xsrf`` input value, which we check on all POST\n        requests to prevent cross-site request forgery. If you have set\n        the ``xsrf_cookies`` application setting, you must include this\n        HTML within all of your HTML forms.\n\n        In a template, this method should be called with ``{% module\n        xsrf_form_html() %}``\n\n        See `check_xsrf_cookie()` above for more information.\n        \"\"\"\n        return '<input type=\"hidden\" name=\"_xsrf\" value=\"' + \\\n            escape.xhtml_escape(self.xsrf_token) + '\"/>'\n\n    def static_url(self, path, include_host=None, **kwargs):\n        \"\"\"Returns a static URL for the given relative static file path.\n\n        This method requires you set the ``static_path`` setting in your\n        application (which specifies the root directory of your static\n        files).\n\n        This method returns a versioned url (by default appending\n        ``?v=<signature>``), which allows the static files to be\n        cached indefinitely.  This can be disabled by passing\n        ``include_version=False`` (in the default implementation;\n        other static file implementations are not required to support\n        this, but they may support other options).\n\n        By default this method returns URLs relative to the current\n        host, but if ``include_host`` is true the URL returned will be\n        absolute.  If this handler has an ``include_host`` attribute,\n        that value will be used as the default for all `static_url`\n        calls that do not pass ``include_host`` as a keyword argument.\n\n        \"\"\"\n        self.require_setting(\"static_path\", \"static_url\")\n        get_url = self.settings.get(\"static_handler_class\",\n                                    StaticFileHandler).make_static_url\n\n        if include_host is None:\n            include_host = getattr(self, \"include_host\", False)\n\n        if include_host:\n            base = self.request.protocol + \"://\" + self.request.host\n        else:\n            base = \"\"\n\n        return base + get_url(self.settings, path, **kwargs)\n\n    def require_setting(self, name, feature=\"this feature\"):\n        \"\"\"Raises an exception if the given app setting is not defined.\"\"\"\n        if not self.application.settings.get(name):\n            raise Exception(\"You must define the '%s' setting in your \"\n                            \"application to use %s\" % (name, feature))\n\n    def reverse_url(self, name, *args):\n        \"\"\"Alias for `Application.reverse_url`.\"\"\"\n        return self.application.reverse_url(name, *args)\n\n    def compute_etag(self):\n        \"\"\"Computes the etag header to be used for this request.\n\n        By default uses a hash of the content written so far.\n\n        May be overridden to provide custom etag implementations,\n        or may return None to disable tornado's default etag support.\n        \"\"\"\n        hasher = hashlib.sha1()\n        for part in self._write_buffer:\n            hasher.update(part)\n        return '\"%s\"' % hasher.hexdigest()\n\n    def set_etag_header(self):\n        \"\"\"Sets the response's Etag header using ``self.compute_etag()``.\n\n        Note: no header will be set if ``compute_etag()`` returns ``None``.\n\n        This method is called automatically when the request is finished.\n        \"\"\"\n        etag = self.compute_etag()\n        if etag is not None:\n            self.set_header(\"Etag\", etag)\n\n    def check_etag_header(self):\n        \"\"\"Checks the ``Etag`` header against requests's ``If-None-Match``.\n\n        Returns ``True`` if the request's Etag matches and a 304 should be\n        returned. For example::\n\n            self.set_etag_header()\n            if self.check_etag_header():\n                self.set_status(304)\n                return\n\n        This method is called automatically when the request is finished,\n        but may be called earlier for applications that override\n        `compute_etag` and want to do an early check for ``If-None-Match``\n        before completing the request.  The ``Etag`` header should be set\n        (perhaps with `set_etag_header`) before calling this method.\n        \"\"\"\n        computed_etag = utf8(self._headers.get(\"Etag\", \"\"))\n        # Find all weak and strong etag values from If-None-Match header\n        # because RFC 7232 allows multiple etag values in a single header.\n        etags = re.findall(\n            br'\\*|(?:W/)?\"[^\"]*\"',\n            utf8(self.request.headers.get(\"If-None-Match\", \"\"))\n        )\n        if not computed_etag or not etags:\n            return False\n\n        match = False\n        if etags[0] == b'*':\n            match = True\n        else:\n            # Use a weak comparison when comparing entity-tags.\n            val = lambda x: x[2:] if x.startswith(b'W/') else x\n            for etag in etags:\n                if val(etag) == val(computed_etag):\n                    match = True\n                    break\n        return match\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    @gen.coroutine\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\n            result = self.prepare()\n            if result is not None:\n                result = yield result\n            if self._prepared_future is not None:\n                # Tell the Application we've finished with prepare()\n                # and are ready for the body to arrive.\n                self._prepared_future.set_result(None)\n            if self._finished:\n                return\n\n            if _has_stream_request_body(self.__class__):\n                # In streaming mode request.body is a Future that signals\n                # the body has been completely received.  The Future has no\n                # result; the data has been passed to self.data_received\n                # instead.\n                try:\n                    yield self.request.body\n                except iostream.StreamClosedError:\n                    return\n\n            method = getattr(self, self.request.method.lower())\n            result = method(*self.path_args, **self.path_kwargs)\n            if result is not None:\n                result = yield result\n            if self._auto_finish and not self._finished:\n                self.finish()\n        except Exception as e:\n            try:\n                self._handle_request_exception(e)\n            except Exception:\n                app_log.error(\"Exception in exception handler\", exc_info=True)\n            if (self._prepared_future is not None and\n                    not self._prepared_future.done()):\n                # In case we failed before setting _prepared_future, do it\n                # now (to unblock the HTTP server).  Note that this is not\n                # in a finally block to avoid GC issues prior to Python 3.4.\n                self._prepared_future.set_result(None)\n\n    def data_received(self, chunk):\n        \"\"\"Implement this method to handle streamed request data.\n\n        Requires the `.stream_request_body` decorator.\n        \"\"\"\n        raise NotImplementedError()\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 \"%s %s (%s)\" % (self.request.method, self.request.uri,\n                               self.request.remote_ip)\n\n    def _handle_request_exception(self, e):\n        if isinstance(e, Finish):\n            # Not an error; just finish the request without logging.\n            if not self._finished:\n                self.finish(*e.args)\n            return\n        try:\n            self.log_exception(*sys.exc_info())\n        except Exception:\n            # An error here should still get a best-effort send_error()\n            # to avoid leaking the connection.\n            app_log.error(\"Error in exception logger\", exc_info=True)\n        if self._finished:\n            # Extra errors after the request has been finished should\n            # be logged, but there is no reason to continue to try and\n            # send a response.\n            return\n        if isinstance(e, HTTPError):\n            if e.status_code not in httputil.responses and not e.reason:\n                gen_log.error(\"Bad HTTP status code: %d\", e.status_code)\n                self.send_error(500, exc_info=sys.exc_info())\n            else:\n                self.send_error(e.status_code, exc_info=sys.exc_info())\n        else:\n            self.send_error(500, exc_info=sys.exc_info())\n\n    def log_exception(self, typ, value, tb):\n        \"\"\"Override to customize logging of uncaught exceptions.\n\n        By default logs instances of `HTTPError` as warnings without\n        stack traces (on the ``tornado.general`` logger), and all\n        other exceptions as errors with stack traces (on the\n        ``tornado.application`` logger).\n\n        .. versionadded:: 3.1\n        \"\"\"\n        if isinstance(value, HTTPError):\n            if value.log_message:\n                format = \"%d %s: \" + value.log_message\n                args = ([value.status_code, self._request_summary()] +\n                        list(value.args))\n                gen_log.warning(format, *args)\n        else:\n            app_log.error(\"Uncaught exception %s\\n%r\", self._request_summary(),\n                          self.request, exc_info=(typ, value, tb))\n\n    def _ui_module(self, name, module):\n        def render(*args, **kwargs):\n            if not hasattr(self, \"_active_modules\"):\n                self._active_modules = {}\n            if name not in self._active_modules:\n                self._active_modules[name] = module(self)\n            rendered = self._active_modules[name].render(*args, **kwargs)\n            return rendered\n        return render\n\n    def _ui_method(self, method):\n        return lambda *args, **kwargs: method(self, *args, **kwargs)\n\n    def _clear_headers_for_304(self):\n        # 304 responses should not contain entity headers (defined in\n        # http://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html#sec7.1)\n        # not explicitly allowed by\n        # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5\n        headers = [\"Allow\", \"Content-Encoding\", \"Content-Language\",\n                   \"Content-Length\", \"Content-MD5\", \"Content-Range\",\n                   \"Content-Type\", \"Last-Modified\"]\n        for h in headers:\n            self.clear_header(h)\n\n\ndef asynchronous(method):\n    \"\"\"Wrap request handler methods with this if they are asynchronous.\n\n    This decorator is for callback-style asynchronous methods; for\n    coroutines, use the ``@gen.coroutine`` decorator without\n    ``@asynchronous``. (It is legal for legacy reasons to use the two\n    decorators together provided ``@asynchronous`` is first, but\n    ``@asynchronous`` will be ignored in this case)\n\n    This decorator should only be applied to the :ref:`HTTP verb\n    methods <verbs>`; its behavior is undefined for any other method.\n    This decorator does not *make* a method asynchronous; it tells\n    the framework that the method *is* asynchronous.  For this decorator\n    to be useful the method must (at least sometimes) do something\n    asynchronous.\n\n    If this decorator is given, the response is not finished when the\n    method returns. It is up to the request handler to call\n    `self.finish() <RequestHandler.finish>` to finish the HTTP\n    request. Without this decorator, the request is automatically\n    finished when the ``get()`` or ``post()`` method returns. Example:\n\n    .. testcode::\n\n       class MyRequestHandler(RequestHandler):\n           @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    .. testoutput::\n       :hide:\n\n    .. versionchanged:: 3.1\n       The ability to use ``@gen.coroutine`` without ``@asynchronous``.\n\n    .. versionchanged:: 4.3 Returning anything but ``None`` or a\n       yieldable object from a method decorated with ``@asynchronous``\n       is an error. Such return values were previously ignored silently.\n    \"\"\"\n    # Delay the IOLoop import because it's not available on app engine.\n    from tornado.ioloop import IOLoop\n\n    @functools.wraps(method)\n    def wrapper(self, *args, **kwargs):\n        self._auto_finish = False\n        with stack_context.ExceptionStackContext(\n                self._stack_context_handle_exception):\n            result = method(self, *args, **kwargs)\n            if result is not None:\n                result = gen.convert_yielded(result)\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                # Once we have done this, hide the Future from our\n                # caller (i.e. RequestHandler._when_complete), which\n                # would otherwise set up its own callback and\n                # exception handler (resulting in exceptions being\n                # logged twice).\n                return None\n            return result\n    return wrapper\n\n\ndef stream_request_body(cls):\n    \"\"\"Apply to `RequestHandler` subclasses to enable streaming body support.\n\n    This decorator implies the following changes:\n\n    * `.HTTPServerRequest.body` is undefined, and body arguments will not\n      be included in `RequestHandler.get_argument`.\n    * `RequestHandler.prepare` is called when the request headers have been\n      read instead of after the entire body has been read.\n    * The subclass must define a method ``data_received(self, data):``, which\n      will be called zero or more times as data is available.  Note that\n      if the request has an empty body, ``data_received`` may not be called.\n    * ``prepare`` and ``data_received`` may return Futures (such as via\n      ``@gen.coroutine``, in which case the next method will not be called\n      until those futures have completed.\n    * The regular HTTP method (``post``, ``put``, etc) will be called after\n      the entire body has been read.\n\n    There is a subtle interaction between ``data_received`` and asynchronous\n    ``prepare``: The first call to ``data_received`` may occur at any point\n    after the call to ``prepare`` has returned *or yielded*.\n    \"\"\"\n    if not issubclass(cls, RequestHandler):\n        raise TypeError(\"expected subclass of RequestHandler, got %r\", cls)\n    cls._stream_request_body = True\n    return cls\n\n\ndef _has_stream_request_body(cls):\n    if not issubclass(cls, RequestHandler):\n        raise TypeError(\"expected subclass of RequestHandler, got %r\", cls)\n    return getattr(cls, '_stream_request_body', False)\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(httputil.HTTPServerConnectionDelegate):\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.current().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    The request class can be specified as either a class object or a\n    (fully-qualified) name.\n\n    Each tuple can contain additional elements, which correspond to the\n    arguments to the `URLSpec` constructor.  (Prior to Tornado 3.2,\n    only tuples of two or three elements were allowed).\n\n    A dictionary may be passed as the third element of the tuple,\n    which will be used as keyword arguments to the handler's\n    constructor and `~RequestHandler.initialize` method.  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    \"\"\"\n    def __init__(self, handlers=None, default_host=\"\", transforms=None,\n                 **settings):\n        if transforms is None:\n            self.transforms = []\n            if settings.get(\"compress_response\") or settings.get(\"gzip\"):\n                self.transforms.append(GZipContentEncoding)\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._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        if self.settings.get('debug'):\n            self.settings.setdefault('autoreload', True)\n            self.settings.setdefault('compiled_template_cache', False)\n            self.settings.setdefault('static_hash_cache', False)\n            self.settings.setdefault('serve_traceback', True)\n\n        # Automatically reload modified modules\n        if self.settings.get('autoreload'):\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.current().start()`` to start the server.\n\n        Returns the `.HTTPServer` object.\n\n        .. versionchanged:: 4.3\n           Now returns the `.HTTPServer` object.\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        return server\n\n    def add_handlers(self, host_pattern, host_handlers):\n        \"\"\"Appends the given handlers to our handler list.\n\n        Host patterns are processed sequentially in the order they were\n        added. All matching patterns will be considered.\n        \"\"\"\n        if not host_pattern.endswith(\"$\"):\n            host_pattern += \"$\"\n        handlers = []\n        # The handlers with the wildcard host_pattern are a special\n        # case - they're added in the constructor but should have lower\n        # precedence than the more-precise handlers added later.\n        # If a wildcard handler group exists, it should always be last\n        # in the list, so insert new groups just before it.\n        if self.handlers and self.handlers[-1][0].pattern == '.*$':\n            self.handlers.insert(-1, (re.compile(host_pattern), handlers))\n        else:\n            self.handlers.append((re.compile(host_pattern), handlers))\n\n        for spec in host_handlers:\n            if isinstance(spec, (tuple, list)):\n                assert len(spec) in (2, 3, 4)\n                spec = URLSpec(*spec)\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 = split_host_and_port(request.host.lower())[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 start_request(self, server_conn, request_conn):\n        # Modern HTTPServer interface\n        return _RequestDispatcher(self, request_conn)\n\n    def __call__(self, request):\n        # Legacy HTTPServer interface\n        dispatcher = _RequestDispatcher(self, None)\n        dispatcher.set_request(request)\n        return dispatcher.execute()\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 _RequestDispatcher(httputil.HTTPMessageDelegate):\n    def __init__(self, application, connection):\n        self.application = application\n        self.connection = connection\n        self.request = None\n        self.chunks = []\n        self.handler_class = None\n        self.handler_kwargs = None\n        self.path_args = []\n        self.path_kwargs = {}\n\n    def headers_received(self, start_line, headers):\n        self.set_request(httputil.HTTPServerRequest(\n            connection=self.connection, start_line=start_line,\n            headers=headers))\n        if self.stream_request_body:\n            self.request.body = Future()\n            return self.execute()\n\n    def set_request(self, request):\n        self.request = request\n        self._find_handler()\n        self.stream_request_body = _has_stream_request_body(self.handler_class)\n\n    def _find_handler(self):\n        # Identify the handler to use as soon as we have the request.\n        # Save url path arguments for later.\n        app = self.application\n        handlers = app._get_host_handlers(self.request)\n        if not handlers:\n            self.handler_class = RedirectHandler\n            self.handler_kwargs = dict(url=\"%s://%s/\"\n                                       % (self.request.protocol,\n                                          app.default_host))\n            return\n        for spec in handlers:\n            match = spec.regex.match(self.request.path)\n            if match:\n                self.handler_class = spec.handler_class\n                self.handler_kwargs = spec.kwargs\n                if spec.regex.groups:\n                    # Pass matched groups to the handler.  Since\n                    # match.groups() includes both named and\n                    # unnamed groups, we want to use either groups\n                    # or groupdict but not both.\n                    if spec.regex.groupindex:\n                        self.path_kwargs = dict(\n                            (str(k), _unquote_or_none(v))\n                            for (k, v) in match.groupdict().items())\n                    else:\n                        self.path_args = [_unquote_or_none(s)\n                                          for s in match.groups()]\n                return\n        if app.settings.get('default_handler_class'):\n            self.handler_class = app.settings['default_handler_class']\n            self.handler_kwargs = app.settings.get(\n                'default_handler_args', {})\n        else:\n            self.handler_class = ErrorHandler\n            self.handler_kwargs = dict(status_code=404)\n\n    def data_received(self, data):\n        if self.stream_request_body:\n            return self.handler.data_received(data)\n        else:\n            self.chunks.append(data)\n\n    def finish(self):\n        if self.stream_request_body:\n            self.request.body.set_result(None)\n        else:\n            self.request.body = b''.join(self.chunks)\n            self.request._parse_body()\n            self.execute()\n\n    def on_connection_close(self):\n        if self.stream_request_body:\n            self.handler.on_connection_close()\n        else:\n            self.chunks = None\n\n    def execute(self):\n        # If template cache is disabled (usually in the debug mode),\n        # re-compile templates and reload static files on every\n        # request so you don't need to restart to see changes\n        if not self.application.settings.get(\"compiled_template_cache\", True):\n            with RequestHandler._template_loader_lock:\n                for loader in RequestHandler._template_loaders.values():\n                    loader.reset()\n        if not self.application.settings.get('static_hash_cache', True):\n            StaticFileHandler.reset()\n\n        self.handler = self.handler_class(self.application, self.request,\n                                          **self.handler_kwargs)\n        transforms = [t(self.request) for t in self.application.transforms]\n\n        if self.stream_request_body:\n            self.handler._prepared_future = Future()\n        # Note that if an exception escapes handler._execute it will be\n        # trapped in the Future it returns (which we are ignoring here,\n        # leaving it to be logged when the Future is GC'd).\n        # However, that shouldn't happen because _execute has a blanket\n        # except handler, and we cannot easily access the IOLoop here to\n        # call add_future (because of the requirement to remain compatible\n        # with WSGI)\n        self.handler._execute(transforms, *self.path_args,\n                              **self.path_kwargs)\n        # If we are streaming the request body, then execute() is finished\n        # when the handler has prepared to receive the body.  If not,\n        # it doesn't matter when execute() finishes (so we return None)\n        return self.handler._prepared_future\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    To customize the response sent with an `HTTPError`, override\n    `RequestHandler.write_error`.\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=500, 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        if log_message and not args:\n            self.log_message = log_message.replace('%', '%%')\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 Finish(Exception):\n    \"\"\"An exception that ends the request without producing an error response.\n\n    When `Finish` is raised in a `RequestHandler`, the request will\n    end (calling `RequestHandler.finish` if it hasn't already been\n    called), but the error-handling methods (including\n    `RequestHandler.write_error`) will not be called.\n\n    If `Finish()` was created with no arguments, the pending response\n    will be sent as-is. If `Finish()` was given an argument, that\n    argument will be passed to `RequestHandler.finish()`.\n\n    This can be a more convenient way to implement custom error pages\n    than overriding ``write_error`` (especially in library code)::\n\n        if self.current_user is None:\n            self.set_status(401)\n            self.set_header('WWW-Authenticate', 'Basic realm=\"something\"')\n            raise Finish()\n\n    .. versionchanged:: 4.3\n       Arguments passed to ``Finish()`` will be passed on to\n       `RequestHandler.finish`.\n    \"\"\"\n    pass\n\n\nclass MissingArgumentError(HTTPError):\n    \"\"\"Exception raised by `RequestHandler.get_argument`.\n\n    This is a subclass of `HTTPError`, so if it is uncaught a 400 response\n    code will be used instead of 500 (and a stack trace will not be logged).\n\n    .. versionadded:: 3.1\n    \"\"\"\n    def __init__(self, arg_name):\n        super(MissingArgumentError, self).__init__(\n            400, 'Missing argument %s' % arg_name)\n        self.arg_name = arg_name\n\n\nclass ErrorHandler(RequestHandler):\n    \"\"\"Generates an error response with ``status_code`` for all requests.\"\"\"\n    def initialize(self, status_code):\n        self.set_status(status_code)\n\n    def prepare(self):\n        raise HTTPError(self._status_code)\n\n    def check_xsrf_cookie(self):\n        # POSTs to an ErrorHandler don't actually have side effects,\n        # so we don't need to check the xsrf token.  This allows POSTs\n        # to the wrong url to return a 404 instead of 403.\n        pass\n\n\nclass RedirectHandler(RequestHandler):\n    \"\"\"Redirects the client to the given URL for all GET requests.\n\n    You should provide the keyword argument ``url`` to the handler, e.g.::\n\n        application = web.Application([\n            (r\"/oldpath\", web.RedirectHandler, {\"url\": \"/newpath\"}),\n        ])\n    \"\"\"\n    def initialize(self, url, permanent=True):\n        self._url = url\n        self._permanent = permanent\n\n    def get(self):\n        self.redirect(self._url, permanent=self._permanent)\n\n\nclass StaticFileHandler(RequestHandler):\n    \"\"\"A simple handler that can serve static content from a directory.\n\n    A `StaticFileHandler` is configured automatically if you pass the\n    ``static_path`` keyword argument to `Application`.  This handler\n    can be customized with the ``static_url_prefix``, ``static_handler_class``,\n    and ``static_handler_args`` settings.\n\n    To map an additional path to this handler for a static data directory\n    you would add a line to your application like::\n\n        application = web.Application([\n            (r\"/content/(.*)\", web.StaticFileHandler, {\"path\": \"/var/www\"}),\n        ])\n\n    The handler constructor requires a ``path`` argument, which specifies the\n    local root directory of the content to be served.\n\n    Note that a capture group in the regex is required to parse the value for\n    the ``path`` argument to the get() method (different than the constructor\n    argument above); see `URLSpec` for details.\n\n    To serve a file like ``index.html`` automatically when a directory is\n    requested, set ``static_handler_args=dict(default_filename=\"index.html\")``\n    in your application settings, or add ``default_filename`` as an initializer\n    argument for your ``StaticFileHandler``.\n\n    To maximize the effectiveness of browser caching, this class supports\n    versioned urls (by default using the argument ``?v=``).  If a version\n    is given, we instruct the browser to cache this file indefinitely.\n    `make_static_url` (also available as `RequestHandler.static_url`) can\n    be used to construct a versioned url.\n\n    This handler is intended primarily for use in development and light-duty\n    file serving; for heavy traffic it will be more efficient to use\n    a dedicated static file server (such as nginx or Apache).  We support\n    the HTTP ``Accept-Ranges`` mechanism to return partial content (because\n    some browsers require this functionality to be present to seek in\n    HTML5 audio or video).\n\n    **Subclassing notes**\n\n    This class is designed to be extensible by subclassing, but because\n    of the way static urls are generated with class methods rather than\n    instance methods, the inheritance patterns are somewhat unusual.\n    Be sure to use the ``@classmethod`` decorator when overriding a\n    class method.  Instance methods may use the attributes ``self.path``\n    ``self.absolute_path``, and ``self.modified``.\n\n    Subclasses should only override methods discussed in this section;\n    overriding other methods is error-prone.  Overriding\n    ``StaticFileHandler.get`` is particularly problematic due to the\n    tight coupling with ``compute_etag`` and other methods.\n\n    To change the way static urls are generated (e.g. to match the behavior\n    of another server or CDN), override `make_static_url`, `parse_url_path`,\n    `get_cache_time`, and/or `get_version`.\n\n    To replace all interaction with the filesystem (e.g. to serve\n    static content from a database), override `get_content`,\n    `get_content_size`, `get_modified_time`, `get_absolute_path`, and\n    `validate_absolute_path`.\n\n    .. versionchanged:: 3.1\n       Many of the methods for subclasses were added in Tornado 3.1.\n    \"\"\"\n    CACHE_MAX_AGE = 86400 * 365 * 10  # 10 years\n\n    _static_hashes = {}\n    _lock = threading.Lock()  # protects _static_hashes\n\n    def initialize(self, path, default_filename=None):\n        self.root = path\n        self.default_filename = default_filename\n\n    @classmethod\n    def reset(cls):\n        with cls._lock:\n            cls._static_hashes = {}\n\n    def head(self, path):\n        return self.get(path, include_body=False)\n\n    @gen.coroutine\n    def get(self, path, include_body=True):\n        # Set up our path instance variables.\n        self.path = self.parse_url_path(path)\n        del path  # make sure we don't refer to path instead of self.path again\n        absolute_path = self.get_absolute_path(self.root, self.path)\n        self.absolute_path = self.validate_absolute_path(\n            self.root, absolute_path)\n        if self.absolute_path is None:\n            return\n\n        self.modified = self.get_modified_time()\n        self.set_headers()\n\n        if self.should_return_304():\n            self.set_status(304)\n            return\n\n        request_range = None\n        range_header = self.request.headers.get(\"Range\")\n        if range_header:\n            # As per RFC 2616 14.16, if an invalid Range header is specified,\n            # the request will be treated as if the header didn't exist.\n            request_range = httputil._parse_request_range(range_header)\n\n        size = self.get_content_size()\n        if request_range:\n            start, end = request_range\n            if (start is not None and start >= size) or end == 0:\n                # As per RFC 2616 14.35.1, a range is not satisfiable only: if\n                # the first requested byte is equal to or greater than the\n                # content, or when a suffix with length 0 is specified\n                self.set_status(416)  # Range Not Satisfiable\n                self.set_header(\"Content-Type\", \"text/plain\")\n                self.set_header(\"Content-Range\", \"bytes */%s\" % (size, ))\n                return\n            if start is not None and start < 0:\n                start += size\n            if end is not None and end > size:\n                # Clients sometimes blindly use a large range to limit their\n                # download size; cap the endpoint at the actual file size.\n                end = size\n            # Note: only return HTTP 206 if less than the entire range has been\n            # requested. Not only is this semantically correct, but Chrome\n            # refuses to play audio if it gets an HTTP 206 in response to\n            # ``Range: bytes=0-``.\n            if size != (end or size) - (start or 0):\n                self.set_status(206)  # Partial Content\n                self.set_header(\"Content-Range\",\n                                httputil._get_content_range(start, end, size))\n        else:\n            start = end = None\n\n        if start is not None and end is not None:\n            content_length = end - start\n        elif end is not None:\n            content_length = end\n        elif start is not None:\n            content_length = size - start\n        else:\n            content_length = size\n        self.set_header(\"Content-Length\", content_length)\n\n        if include_body:\n            content = self.get_content(self.absolute_path, start, end)\n            if isinstance(content, bytes):\n                content = [content]\n            for chunk in content:\n                try:\n                    self.write(chunk)\n                    yield self.flush()\n                except iostream.StreamClosedError:\n                    return\n        else:\n            assert self.request.method == \"HEAD\"\n\n    def compute_etag(self):\n        \"\"\"Sets the ``Etag`` header based on static url version.\n\n        This allows efficient ``If-None-Match`` checks against cached\n        versions, and sends the correct ``Etag`` for a partial response\n        (i.e. the same ``Etag`` as the full file).\n\n        .. versionadded:: 3.1\n        \"\"\"\n        version_hash = self._get_cached_version(self.absolute_path)\n        if not version_hash:\n            return None\n        return '\"%s\"' % (version_hash, )\n\n    def set_headers(self):\n        \"\"\"Sets the content and caching headers on the response.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        self.set_header(\"Accept-Ranges\", \"bytes\")\n        self.set_etag_header()\n\n        if self.modified is not None:\n            self.set_header(\"Last-Modified\", self.modified)\n\n        content_type = self.get_content_type()\n        if content_type:\n            self.set_header(\"Content-Type\", content_type)\n\n        cache_time = self.get_cache_time(self.path, self.modified,\n                                         content_type)\n        if cache_time > 0:\n            self.set_header(\"Expires\", datetime.datetime.utcnow() +\n                            datetime.timedelta(seconds=cache_time))\n            self.set_header(\"Cache-Control\", \"max-age=\" + str(cache_time))\n\n        self.set_extra_headers(self.path)\n\n    def should_return_304(self):\n        \"\"\"Returns True if the headers indicate that we should return 304.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        if self.check_etag_header():\n            return True\n\n        # Check the If-Modified-Since, and don't send the result if the\n        # content has not been modified\n        ims_value = self.request.headers.get(\"If-Modified-Since\")\n        if ims_value is not None:\n            date_tuple = email.utils.parsedate(ims_value)\n            if date_tuple is not None:\n                if_since = datetime.datetime(*date_tuple[:6])\n                if if_since >= self.modified:\n                    return True\n\n        return False\n\n    @classmethod\n    def get_absolute_path(cls, root, path):\n        \"\"\"Returns the absolute location of ``path`` relative to ``root``.\n\n        ``root`` is the path configured for this `StaticFileHandler`\n        (in most cases the ``static_path`` `Application` setting).\n\n        This class method may be overridden in subclasses.  By default\n        it returns a filesystem path, but other strings may be used\n        as long as they are unique and understood by the subclass's\n        overridden `get_content`.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        abspath = os.path.abspath(os.path.join(root, path))\n        return abspath\n\n    def validate_absolute_path(self, root, absolute_path):\n        \"\"\"Validate and return the absolute path.\n\n        ``root`` is the configured path for the `StaticFileHandler`,\n        and ``path`` is the result of `get_absolute_path`\n\n        This is an instance method called during request processing,\n        so it may raise `HTTPError` or use methods like\n        `RequestHandler.redirect` (return None after redirecting to\n        halt further processing).  This is where 404 errors for missing files\n        are generated.\n\n        This method may modify the path before returning it, but note that\n        any such modifications will not be understood by `make_static_url`.\n\n        In instance methods, this method's result is available as\n        ``self.absolute_path``.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        # os.path.abspath strips a trailing /.\n        # We must add it back to `root` so that we only match files\n        # in a directory named `root` instead of files starting with\n        # that prefix.\n        root = os.path.abspath(root)\n        if not root.endswith(os.path.sep):\n            # abspath always removes a trailing slash, except when\n            # root is '/'. This is an unusual case, but several projects\n            # have independently discovered this technique to disable\n            # Tornado's path validation and (hopefully) do their own,\n            # so we need to support it.\n            root += os.path.sep\n        # The trailing slash also needs to be temporarily added back\n        # the requested path so a request to root/ will match.\n        if not (absolute_path + os.path.sep).startswith(root):\n            raise HTTPError(403, \"%s is not in root static directory\",\n                            self.path)\n        if (os.path.isdir(absolute_path) and\n                self.default_filename is not None):\n            # need to look at the request.path here for when path is empty\n            # but there is some prefix to the path that was already\n            # trimmed by the routing\n            if not self.request.path.endswith(\"/\"):\n                self.redirect(self.request.path + \"/\", permanent=True)\n                return\n            absolute_path = os.path.join(absolute_path, self.default_filename)\n        if not os.path.exists(absolute_path):\n            raise HTTPError(404)\n        if not os.path.isfile(absolute_path):\n            raise HTTPError(403, \"%s is not a file\", self.path)\n        return absolute_path\n\n    @classmethod\n    def get_content(cls, abspath, start=None, end=None):\n        \"\"\"Retrieve the content of the requested resource which is located\n        at the given absolute path.\n\n        This class method may be overridden by subclasses.  Note that its\n        signature is different from other overridable class methods\n        (no ``settings`` argument); this is deliberate to ensure that\n        ``abspath`` is able to stand on its own as a cache key.\n\n        This method should either return a byte string or an iterator\n        of byte strings.  The latter is preferred for large files\n        as it helps reduce memory fragmentation.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        with open(abspath, \"rb\") as file:\n            if start is not None:\n                file.seek(start)\n            if end is not None:\n                remaining = end - (start or 0)\n            else:\n                remaining = None\n            while True:\n                chunk_size = 64 * 1024\n                if remaining is not None and remaining < chunk_size:\n                    chunk_size = remaining\n                chunk = file.read(chunk_size)\n                if chunk:\n                    if remaining is not None:\n                        remaining -= len(chunk)\n                    yield chunk\n                else:\n                    if remaining is not None:\n                        assert remaining == 0\n                    return\n\n    @classmethod\n    def get_content_version(cls, abspath):\n        \"\"\"Returns a version string for the resource at the given path.\n\n        This class method may be overridden by subclasses.  The\n        default implementation is a hash of the file's contents.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        data = cls.get_content(abspath)\n        hasher = hashlib.md5()\n        if isinstance(data, bytes):\n            hasher.update(data)\n        else:\n            for chunk in data:\n                hasher.update(chunk)\n        return hasher.hexdigest()\n\n    def _stat(self):\n        if not hasattr(self, '_stat_result'):\n            self._stat_result = os.stat(self.absolute_path)\n        return self._stat_result\n\n    def get_content_size(self):\n        \"\"\"Retrieve the total size of the resource at the given path.\n\n        This method may be overridden by subclasses.\n\n        .. versionadded:: 3.1\n\n        .. versionchanged:: 4.0\n           This method is now always called, instead of only when\n           partial results are requested.\n        \"\"\"\n        stat_result = self._stat()\n        return stat_result[stat.ST_SIZE]\n\n    def get_modified_time(self):\n        \"\"\"Returns the time that ``self.absolute_path`` was last modified.\n\n        May be overridden in subclasses.  Should return a `~datetime.datetime`\n        object or None.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        stat_result = self._stat()\n        modified = datetime.datetime.utcfromtimestamp(\n            stat_result[stat.ST_MTIME])\n        return modified\n\n    def get_content_type(self):\n        \"\"\"Returns the ``Content-Type`` header to be used for this request.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        mime_type, encoding = mimetypes.guess_type(self.absolute_path)\n        # per RFC 6713, use the appropriate type for a gzip compressed file\n        if encoding == \"gzip\":\n            return \"application/gzip\"\n        # As of 2015-07-21 there is no bzip2 encoding defined at\n        # http://www.iana.org/assignments/media-types/media-types.xhtml\n        # So for that (and any other encoding), use octet-stream.\n        elif encoding is not None:\n            return \"application/octet-stream\"\n        elif mime_type is not None:\n            return mime_type\n        # if mime_type not detected, use application/octet-stream\n        else:\n            return \"application/octet-stream\"\n\n    def set_extra_headers(self, path):\n        \"\"\"For subclass to add extra headers to the response\"\"\"\n        pass\n\n    def get_cache_time(self, path, modified, mime_type):\n        \"\"\"Override to customize cache control behavior.\n\n        Return a positive number of seconds to make the result\n        cacheable for that amount of time or 0 to mark resource as\n        cacheable for an unspecified amount of time (subject to\n        browser heuristics).\n\n        By default returns cache expiry of 10 years for resources requested\n        with ``v`` argument.\n        \"\"\"\n        return self.CACHE_MAX_AGE if \"v\" in self.request.arguments else 0\n\n    @classmethod\n    def make_static_url(cls, settings, path, include_version=True):\n        \"\"\"Constructs a versioned url for the given path.\n\n        This method may be overridden in subclasses (but note that it\n        is a class method rather than an instance method).  Subclasses\n        are only required to implement the signature\n        ``make_static_url(cls, settings, path)``; other keyword\n        arguments may be passed through `~RequestHandler.static_url`\n        but are not standard.\n\n        ``settings`` is the `Application.settings` dictionary.  ``path``\n        is the static path being requested.  The url returned should be\n        relative to the current host.\n\n        ``include_version`` determines whether the generated URL should\n        include the query string containing the version hash of the\n        file corresponding to the given ``path``.\n\n        \"\"\"\n        url = settings.get('static_url_prefix', '/static/') + path\n        if not include_version:\n            return url\n\n        version_hash = cls.get_version(settings, path)\n        if not version_hash:\n            return url\n\n        return '%s?v=%s' % (url, version_hash)\n\n    def parse_url_path(self, url_path):\n        \"\"\"Converts a static URL path into a filesystem path.\n\n        ``url_path`` is the path component of the URL with\n        ``static_url_prefix`` removed.  The return value should be\n        filesystem path relative to ``static_path``.\n\n        This is the inverse of `make_static_url`.\n        \"\"\"\n        if os.path.sep != \"/\":\n            url_path = url_path.replace(\"/\", os.path.sep)\n        return url_path\n\n    @classmethod\n    def get_version(cls, settings, path):\n        \"\"\"Generate the version string to be used in static URLs.\n\n        ``settings`` is the `Application.settings` dictionary and ``path``\n        is the relative location of the requested asset on the filesystem.\n        The returned value should be a string, or ``None`` if no version\n        could be determined.\n\n        .. versionchanged:: 3.1\n           This method was previously recommended for subclasses to override;\n           `get_content_version` is now preferred as it allows the base\n           class to handle caching of the result.\n        \"\"\"\n        abs_path = cls.get_absolute_path(settings['static_path'], path)\n        return cls._get_cached_version(abs_path)\n\n    @classmethod\n    def _get_cached_version(cls, abs_path):\n        with cls._lock:\n            hashes = cls._static_hashes\n            if abs_path not in hashes:\n                try:\n                    hashes[abs_path] = cls.get_content_version(abs_path)\n                except Exception:\n                    gen_log.error(\"Could not open static file %r\", abs_path)\n                    hashes[abs_path] = None\n            hsh = hashes.get(abs_path)\n            if hsh:\n                return hsh\n        return None\n\n\nclass FallbackHandler(RequestHandler):\n    \"\"\"A `RequestHandler` that wraps another HTTP server callback.\n\n    The fallback is a callable object that accepts an\n    `~.httputil.HTTPServerRequest`, 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    Applications are not expected to create their own OutputTransforms\n    or interact with them directly; the framework chooses which transforms\n    (if any) to apply.\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    .. versionchanged:: 4.0\n        Now compresses all mime types beginning with ``text/``, instead\n        of just a whitelist. (the whitelist is still used for certain\n        non-text mime types).\n    \"\"\"\n    # Whitelist of compressible mime types (in addition to any types\n    # beginning with \"text/\").\n    CONTENT_TYPES = set([\"application/javascript\", \"application/x-javascript\",\n                         \"application/xml\", \"application/atom+xml\",\n                         \"application/json\", \"application/xhtml+xml\"])\n    # Python's GzipFile defaults to level 9, while most other gzip\n    # tools (including gzip itself) default to 6, which is probably a\n    # better CPU/size tradeoff.\n    GZIP_LEVEL = 6\n    # Responses that are too short are unlikely to benefit from gzipping\n    # after considering the \"Content-Encoding: gzip\" header and the header\n    # inside the gzip encoding.\n    # Note that responses written in multiple chunks will be compressed\n    # regardless of size.\n    MIN_LENGTH = 1024\n\n    def __init__(self, request):\n        self._gzipping = \"gzip\" in request.headers.get(\"Accept-Encoding\", \"\")\n\n    def _compressible_type(self, ctype):\n        return ctype.startswith('text/') or ctype in self.CONTENT_TYPES\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 = self._compressible_type(ctype) and \\\n                (not finishing or len(chunk) >= self.MIN_LENGTH) 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                                            compresslevel=self.GZIP_LEVEL)\n            chunk = self.transform_chunk(chunk, finishing)\n            if \"Content-Length\" in headers:\n                # The original content length is no longer correct.\n                # If this is the last (and only) chunk, we can set the new\n                # content-length; otherwise we remove it and fall back to\n                # chunked encoding.\n                if finishing:\n                    headers[\"Content-Length\"] = str(len(chunk))\n                else:\n                    del headers[\"Content-Length\"]\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\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    If you configure a login url with a query parameter, Tornado will\n    assume you know what you're doing and use it as-is.  If not, it\n    will add a `next` parameter so the login page knows where to send\n    you once you're logged in.\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    Subclasses of UIModule must override the `render` method.\n    \"\"\"\n    def __init__(self, handler):\n        self.handler = handler\n        self.request = handler.request\n        self.ui = handler.ui\n        self.locale = handler.locale\n\n    @property\n    def current_user(self):\n        return self.handler.current_user\n\n    def render(self, *args, **kwargs):\n        \"\"\"Override in subclasses to return this module's output.\"\"\"\n        raise NotImplementedError()\n\n    def embedded_javascript(self):\n        \"\"\"Override to return a JavaScript string\n        to be embedded in the page.\"\"\"\n        return None\n\n    def javascript_files(self):\n        \"\"\"Override to return a list of JavaScript files needed by this module.\n\n        If the return values are relative paths, they will be passed to\n        `RequestHandler.static_url`; otherwise they will be used as-is.\n        \"\"\"\n        return None\n\n    def embedded_css(self):\n        \"\"\"Override to return a CSS string\n        that will be embedded in the page.\"\"\"\n        return None\n\n    def css_files(self):\n        \"\"\"Override to returns a list of CSS files required by this module.\n\n        If the return values are relative paths, they will be passed to\n        `RequestHandler.static_url`; otherwise they will be used as-is.\n        \"\"\"\n        return None\n\n    def html_head(self):\n        \"\"\"Override to return an HTML string that will be put in the <head/>\n        element.\n        \"\"\"\n        return None\n\n    def html_body(self):\n        \"\"\"Override to return an HTML string that will be put at the end of\n        the <body/> element.\n        \"\"\"\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)):\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)):\n                result.append(f)\n            else:\n                result.extend(f)\n        return result\n\n    def html_head(self):\n        return \"\".join(self._get_resources(\"html_head\"))\n\n    def html_body(self):\n        return \"\".join(self._get_resources(\"html_body\"))\n\n\nclass _UIModuleNamespace(object):\n    \"\"\"Lazy namespace which creates UIModule proxies bound to a handler.\"\"\"\n    def __init__(self, handler, ui_modules):\n        self.handler = handler\n        self.ui_modules = ui_modules\n\n    def __getitem__(self, key):\n        return self.handler._ui_module(key, self.ui_modules[key])\n\n    def __getattr__(self, key):\n        try:\n            return self[key]\n        except KeyError as e:\n            raise AttributeError(str(e))\n\n\nclass URLSpec(object):\n    \"\"\"Specifies mappings between URLs and handlers.\"\"\"\n    def __init__(self, pattern, handler, 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``: `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\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        self.handler_class = handler\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(re_unescape(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)):\n                a = str(a)\n            converted_args.append(escape.url_escape(utf8(a), plus=False))\n        return self._path % tuple(converted_args)\n\nurl = URLSpec\n\n\nif hasattr(hmac, 'compare_digest'):  # python 3.3\n    _time_independent_equals = hmac.compare_digest\nelse:\n    def _time_independent_equals(a, b):\n        if len(a) != len(b):\n            return False\n        result = 0\n        if isinstance(a[0], int):  # python3 byte strings\n            for x, y in zip(a, b):\n                result |= x ^ y\n        else:  # python2\n            for x, y in zip(a, b):\n                result |= ord(x) ^ ord(y)\n        return result == 0\n\n\ndef create_signed_value(secret, name, value, version=None, clock=None,\n                        key_version=None):\n    if version is None:\n        version = DEFAULT_SIGNED_VALUE_VERSION\n    if clock is None:\n        clock = time.time\n\n    timestamp = utf8(str(int(clock())))\n    value = base64.b64encode(utf8(value))\n    if version == 1:\n        signature = _create_signature_v1(secret, name, value, timestamp)\n        value = b\"|\".join([value, timestamp, signature])\n        return value\n    elif version == 2:\n        # The v2 format consists of a version number and a series of\n        # length-prefixed fields \"%d:%s\", the last of which is a\n        # signature, all separated by pipes.  All numbers are in\n        # decimal format with no leading zeros.  The signature is an\n        # HMAC-SHA256 of the whole string up to that point, including\n        # the final pipe.\n        #\n        # The fields are:\n        # - format version (i.e. 2; no length prefix)\n        # - key version (integer, default is 0)\n        # - timestamp (integer seconds since epoch)\n        # - name (not encoded; assumed to be ~alphanumeric)\n        # - value (base64-encoded)\n        # - signature (hex-encoded; no length prefix)\n        def format_field(s):\n            return utf8(\"%d:\" % len(s)) + utf8(s)\n        to_sign = b\"|\".join([\n            b\"2\",\n            format_field(str(key_version or 0)),\n            format_field(timestamp),\n            format_field(name),\n            format_field(value),\n            b''])\n\n        if isinstance(secret, dict):\n            assert key_version is not None, 'Key version must be set when sign key dict is used'\n            assert version >= 2, 'Version must be at least 2 for key version support'\n            secret = secret[key_version]\n\n        signature = _create_signature_v2(secret, to_sign)\n        return to_sign + signature\n    else:\n        raise ValueError(\"Unsupported version %d\" % version)\n\n# A leading version number in decimal\n# with no leading zeros, followed by a pipe.\n_signed_value_version_re = re.compile(br\"^([1-9][0-9]*)\\|(.*)$\")\n\n\ndef _get_version(value):\n    # Figures out what version value is.  Version 1 did not include an\n    # explicit version field and started with arbitrary base64 data,\n    # which makes this tricky.\n    m = _signed_value_version_re.match(value)\n    if m is None:\n        version = 1\n    else:\n        try:\n            version = int(m.group(1))\n            if version > 999:\n                # Certain payloads from the version-less v1 format may\n                # be parsed as valid integers.  Due to base64 padding\n                # restrictions, this can only happen for numbers whose\n                # length is a multiple of 4, so we can treat all\n                # numbers up to 999 as versions, and for the rest we\n                # fall back to v1 format.\n                version = 1\n        except ValueError:\n            version = 1\n    return version\n\n\ndef decode_signed_value(secret, name, value, max_age_days=31,\n                        clock=None, min_version=None):\n    if clock is None:\n        clock = time.time\n    if min_version is None:\n        min_version = DEFAULT_SIGNED_VALUE_MIN_VERSION\n    if min_version > 2:\n        raise ValueError(\"Unsupported min_version %d\" % min_version)\n    if not value:\n        return None\n\n    value = utf8(value)\n    version = _get_version(value)\n\n    if version < min_version:\n        return None\n    if version == 1:\n        return _decode_signed_value_v1(secret, name, value,\n                                       max_age_days, clock)\n    elif version == 2:\n        return _decode_signed_value_v2(secret, name, value,\n                                       max_age_days, clock)\n    else:\n        return None\n\n\ndef _decode_signed_value_v1(secret, name, value, max_age_days, clock):\n    parts = utf8(value).split(b\"|\")\n    if len(parts) != 3:\n        return None\n    signature = _create_signature_v1(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 < clock() - max_age_days * 86400:\n        gen_log.warning(\"Expired cookie %r\", value)\n        return None\n    if timestamp > clock() + 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\",\n                        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 _decode_fields_v2(value):\n    def _consume_field(s):\n        length, _, rest = s.partition(b':')\n        n = int(length)\n        field_value = rest[:n]\n        # In python 3, indexing bytes returns small integers; we must\n        # use a slice to get a byte string as in python 2.\n        if rest[n:n + 1] != b'|':\n            raise ValueError(\"malformed v2 signed value field\")\n        rest = rest[n + 1:]\n        return field_value, rest\n\n    rest = value[2:]  # remove version number\n    key_version, rest = _consume_field(rest)\n    timestamp, rest = _consume_field(rest)\n    name_field, rest = _consume_field(rest)\n    value_field, passed_sig = _consume_field(rest)\n    return int(key_version), timestamp, name_field, value_field, passed_sig\n\n\ndef _decode_signed_value_v2(secret, name, value, max_age_days, clock):\n    try:\n        key_version, timestamp, name_field, value_field, passed_sig = _decode_fields_v2(value)\n    except ValueError:\n        return None\n    signed_string = value[:-len(passed_sig)]\n\n    if isinstance(secret, dict):\n        try:\n            secret = secret[key_version]\n        except KeyError:\n            return None\n\n    expected_sig = _create_signature_v2(secret, signed_string)\n    if not _time_independent_equals(passed_sig, expected_sig):\n        return None\n    if name_field != utf8(name):\n        return None\n    timestamp = int(timestamp)\n    if timestamp < clock() - max_age_days * 86400:\n        # The signature has expired.\n        return None\n    try:\n        return base64.b64decode(value_field)\n    except Exception:\n        return None\n\n\ndef get_signature_key_version(value):\n    value = utf8(value)\n    version = _get_version(value)\n    if version < 2:\n        return None\n    try:\n        key_version, _, _, _, _ = _decode_fields_v2(value)\n    except ValueError:\n        return None\n\n    return key_version\n\n\ndef _create_signature_v1(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\n\ndef _create_signature_v2(secret, s):\n    hash = hmac.new(utf8(secret), digestmod=hashlib.sha256)\n    hash.update(utf8(s))\n    return utf8(hash.hexdigest())\n\n\ndef _unquote_or_none(s):\n    \"\"\"None-safe wrapper around url_unescape to handle unamteched optional\n    groups correctly.\n\n    Note that args are passed as bytes so the handler can decide what\n    encoding to use.\n    \"\"\"\n    if s is None:\n        return s\n    return escape.url_unescape(s, encoding=None, plus=False)\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.. testcode::\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.current().start()\n\n.. testoutput::\n   :hide:\n\n\nSee the :doc:`guide` for additional information.\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\"\"\"\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\nfrom io import BytesIO\n\nfrom tornado.concurrent import Future\nfrom tornado import escape\nfrom tornado import gen\nfrom tornado import httputil\nfrom tornado import iostream\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 (import_object, ObjectDict, raise_exc_info,\n                          unicode_type, _websocket_mask, re_unescape)\nfrom tornado.httputil import split_host_and_port\n\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\nMIN_SUPPORTED_SIGNED_VALUE_VERSION = 1\n\"\"\"The oldest signed value version supported by this version of Tornado.\n\nSigned values older than this version cannot be decoded.\n\n.. versionadded:: 3.2.1\n\"\"\"\n\nMAX_SUPPORTED_SIGNED_VALUE_VERSION = 2\n\"\"\"The newest signed value version supported by this version of Tornado.\n\nSigned values newer than this version cannot be decoded.\n\n.. versionadded:: 3.2.1\n\"\"\"\n\nDEFAULT_SIGNED_VALUE_VERSION = 2\n\"\"\"The signed value version produced by `.RequestHandler.create_signed_value`.\n\nMay be overridden by passing a ``version`` keyword argument.\n\n.. versionadded:: 3.2.1\n\"\"\"\n\nDEFAULT_SIGNED_VALUE_MIN_VERSION = 1\n\"\"\"The oldest signed value accepted by `.RequestHandler.get_secure_cookie`.\n\nMay be overridden by passing a ``min_version`` keyword argument.\n\n.. versionadded:: 3.2.1\n\"\"\"\n\n\nclass RequestHandler(object):\n    \"\"\"Base class for HTTP request handlers.\n\n    Subclasses must define at least one of the methods defined in the\n    \"Entry points\" section below.\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._prepared_future = None\n        self.path_args = None\n        self.path_kwargs = None\n        self.ui = ObjectDict((n, self._ui_method(m)) for n, m in\n                             application.ui_methods.items())\n        # UIModules are available as both `modules` and `_tt_modules` in the\n        # template namespace.  Historically only `modules` was available\n        # but could be clobbered by user additions to the namespace.\n        # The template {% module %} directive looks in `_tt_modules` to avoid\n        # possible conflicts.\n        self.ui[\"_tt_modules\"] = _UIModuleNamespace(self,\n                                                    application.ui_modules)\n        self.ui[\"modules\"] = self.ui[\"_tt_modules\"]\n        self.clear()\n        self.request.connection.set_close_callback(self.on_connection_close)\n        self.initialize(**kwargs)\n\n    def initialize(self):\n        \"\"\"Hook for subclass initialization. Called for each request.\n\n        A dictionary passed as the third argument of a url spec will be\n        supplied as keyword arguments to initialize().\n\n        Example::\n\n            class ProfileHandler(RequestHandler):\n                def initialize(self, database):\n                    self.database = database\n\n                def get(self, username):\n                    ...\n\n            app = Application([\n                (r'/user/(.*)', ProfileHandler, dict(database=database)),\n                ])\n        \"\"\"\n        pass\n\n    @property\n    def settings(self):\n        \"\"\"An alias for `self.application.settings <Application.settings>`.\"\"\"\n        return self.application.settings\n\n    def head(self, *args, **kwargs):\n        raise HTTPError(405)\n\n    def get(self, *args, **kwargs):\n        raise HTTPError(405)\n\n    def post(self, *args, **kwargs):\n        raise HTTPError(405)\n\n    def delete(self, *args, **kwargs):\n        raise HTTPError(405)\n\n    def patch(self, *args, **kwargs):\n        raise HTTPError(405)\n\n    def put(self, *args, **kwargs):\n        raise HTTPError(405)\n\n    def options(self, *args, **kwargs):\n        raise HTTPError(405)\n\n    def prepare(self):\n        \"\"\"Called at the beginning of a request before  `get`/`post`/etc.\n\n        Override this method to perform common initialization regardless\n        of the request method.\n\n        Asynchronous support: Decorate this method with `.gen.coroutine`\n        or `.return_future` to make it asynchronous (the\n        `asynchronous` decorator cannot be used on `prepare`).\n        If this method returns a `.Future` execution will not proceed\n        until the `.Future` is done.\n\n        .. versionadded:: 3.1\n           Asynchronous support.\n        \"\"\"\n        pass\n\n    def on_finish(self):\n        \"\"\"Called after the end of a request.\n\n        Override this method to perform cleanup, logging, etc.\n        This method is a counterpart to `prepare`.  ``on_finish`` may\n        not produce any output, as it is called after the response\n        has been sent to the client.\n        \"\"\"\n        pass\n\n    def on_connection_close(self):\n        \"\"\"Called in async handlers if the client closed the connection.\n\n        Override this to clean up resources associated with\n        long-lived connections.  Note that this method is called only if\n        the connection was closed during asynchronous processing; if you\n        need to do cleanup after every request override `on_finish`\n        instead.\n\n        Proxies may keep a connection open for a time (perhaps\n        indefinitely) after the client has gone away, so this method\n        may not be called promptly after the end user closes their\n        connection.\n        \"\"\"\n        if _has_stream_request_body(self.__class__):\n            if not self.request.body.done():\n                self.request.body.set_exception(iostream.StreamClosedError())\n                self.request.body.exception()\n\n    def clear(self):\n        \"\"\"Resets all headers and content for this response.\"\"\"\n        self._headers = httputil.HTTPHeaders({\n            \"Server\": \"TornadoServer/%s\" % tornado.version,\n            \"Content-Type\": \"text/html; charset=UTF-8\",\n            \"Date\": httputil.format_timestamp(time.time()),\n        })\n        self.set_default_headers()\n        self._write_buffer = []\n        self._status_code = 200\n        self._reason = httputil.responses[200]\n\n    def set_default_headers(self):\n        \"\"\"Override this to set HTTP headers at the beginning of the request.\n\n        For example, this is the place to set a custom ``Server`` header.\n        Note that setting such headers in the normal flow of request\n        processing may not do what you want, since headers may be reset\n        during error handling.\n        \"\"\"\n        pass\n\n    def set_status(self, status_code, reason=None):\n        \"\"\"Sets the status code for our response.\n\n        :arg int status_code: Response status code. If ``reason`` is ``None``,\n            it must be present in `httplib.responses <http.client.responses>`.\n        :arg string reason: Human-readable reason phrase describing the status\n            code. If ``None``, it will be filled in from\n            `httplib.responses <http.client.responses>`.\n        \"\"\"\n        self._status_code = status_code\n        if reason is not None:\n            self._reason = escape.native_str(reason)\n        else:\n            try:\n                self._reason = httputil.responses[status_code]\n            except KeyError:\n                raise ValueError(\"unknown status code %d\", status_code)\n\n    def get_status(self):\n        \"\"\"Returns the status code for our response.\"\"\"\n        return self._status_code\n\n    def set_header(self, name, value):\n        \"\"\"Sets the given response header name and value.\n\n        If a datetime is given, we automatically format it according to the\n        HTTP specification. If the value is not a string, we convert it to\n        a string. All header values are then encoded as UTF-8.\n        \"\"\"\n        self._headers[name] = self._convert_header_value(value)\n\n    def add_header(self, name, value):\n        \"\"\"Adds the given response header and value.\n\n        Unlike `set_header`, `add_header` may be called multiple times\n        to return multiple values for the same header.\n        \"\"\"\n        self._headers.add(name, self._convert_header_value(value))\n\n    def clear_header(self, name):\n        \"\"\"Clears an outgoing header, undoing a previous `set_header` call.\n\n        Note that this method does not apply to multi-valued headers\n        set by `add_header`.\n        \"\"\"\n        if name in self._headers:\n            del self._headers[name]\n\n    _INVALID_HEADER_CHAR_RE = re.compile(br\"[\\x00-\\x1f]\")\n\n    def _convert_header_value(self, value):\n        if isinstance(value, bytes):\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.\n        if RequestHandler._INVALID_HEADER_CHAR_RE.search(value):\n            raise ValueError(\"Unsafe header value %r\", value)\n        return value\n\n    _ARG_DEFAULT = []\n\n    def get_argument(self, name, default=_ARG_DEFAULT, strip=True):\n        \"\"\"Returns the value of the argument with the given name.\n\n        If default is not provided, the argument is considered to be\n        required, and we raise a `MissingArgumentError` if it is missing.\n\n        If the argument appears in the url more than once, we return the\n        last value.\n\n        The returned value is always unicode.\n        \"\"\"\n        return self._get_argument(name, default, self.request.arguments, strip)\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        # Make sure `get_arguments` isn't accidentally being called with a\n        # positional argument that's assumed to be a default (like in\n        # `get_argument`.)\n        assert isinstance(strip, bool)\n\n        return self._get_arguments(name, self.request.arguments, strip)\n\n    def get_body_argument(self, name, default=_ARG_DEFAULT, strip=True):\n        \"\"\"Returns the value of the argument with the given name\n        from the request body.\n\n        If default is not provided, the argument is considered to be\n        required, and we raise a `MissingArgumentError` if it is missing.\n\n        If the argument appears in the url more than once, we return the\n        last value.\n\n        The returned value is always unicode.\n\n        .. versionadded:: 3.2\n        \"\"\"\n        return self._get_argument(name, default, self.request.body_arguments,\n                                  strip)\n\n    def get_body_arguments(self, name, strip=True):\n        \"\"\"Returns a list of the body 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        .. versionadded:: 3.2\n        \"\"\"\n        return self._get_arguments(name, self.request.body_arguments, strip)\n\n    def get_query_argument(self, name, default=_ARG_DEFAULT, strip=True):\n        \"\"\"Returns the value of the argument with the given name\n        from the request query string.\n\n        If default is not provided, the argument is considered to be\n        required, and we raise a `MissingArgumentError` if it is missing.\n\n        If the argument appears in the url more than once, we return the\n        last value.\n\n        The returned value is always unicode.\n\n        .. versionadded:: 3.2\n        \"\"\"\n        return self._get_argument(name, default,\n                                  self.request.query_arguments, strip)\n\n    def get_query_arguments(self, name, strip=True):\n        \"\"\"Returns a list of the query 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        .. versionadded:: 3.2\n        \"\"\"\n        return self._get_arguments(name, self.request.query_arguments, strip)\n\n    def _get_argument(self, name, default, source, strip=True):\n        args = self._get_arguments(name, source, strip=strip)\n        if not args:\n            if default is self._ARG_DEFAULT:\n                raise MissingArgumentError(name)\n            return default\n        return args[-1]\n\n    def _get_arguments(self, name, source, strip=True):\n        values = []\n        for v in source.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        try:\n            return _unicode(value)\n        except UnicodeDecodeError:\n            raise HTTPError(400, \"Invalid unicode in %s: %r\" %\n                            (name or \"url\", value[:40]))\n\n    @property\n    def cookies(self):\n        \"\"\"An alias for\n        `self.request.cookies <.httputil.HTTPServerRequest.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\n            # skip falsy values for httponly and secure flags because\n            # SimpleCookie sets them regardless\n            if k in ['httponly', 'secure'] and not v:\n                continue\n\n            morsel[k] = v\n\n    def clear_cookie(self, name, path=\"/\", domain=None):\n        \"\"\"Deletes the cookie with the given name.\n\n        Due to limitations of the cookie protocol, you must pass the same\n        path and domain to clear a cookie as were used when that cookie\n        was set (but there is no way to find out on the server side\n        which values were used for a given cookie).\n        \"\"\"\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, path=\"/\", domain=None):\n        \"\"\"Deletes all the cookies the user sent with this request.\n\n        See `clear_cookie` for more information on the path and domain\n        parameters.\n\n        .. versionchanged:: 3.2\n\n           Added the ``path`` and ``domain`` parameters.\n        \"\"\"\n        for name in self.request.cookies:\n            self.clear_cookie(name, path=path, domain=domain)\n\n    def set_secure_cookie(self, name, value, expires_days=30, version=None,\n                          **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        .. versionchanged:: 3.2.1\n\n           Added the ``version`` argument.  Introduced cookie version 2\n           and made it the default.\n        \"\"\"\n        self.set_cookie(name, self.create_signed_value(name, value,\n                                                       version=version),\n                        expires_days=expires_days, **kwargs)\n\n    def create_signed_value(self, name, value, version=None):\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        .. versionchanged:: 3.2.1\n\n           Added the ``version`` argument.  Introduced cookie version 2\n           and made it the default.\n        \"\"\"\n        self.require_setting(\"cookie_secret\", \"secure cookies\")\n        secret = self.application.settings[\"cookie_secret\"]\n        key_version = None\n        if isinstance(secret, dict):\n            if self.application.settings.get(\"key_version\") is None:\n                raise Exception(\"key_version setting must be used for secret_key dicts\")\n            key_version = self.application.settings[\"key_version\"]\n\n        return create_signed_value(secret, name, value, version=version,\n                                   key_version=key_version)\n\n    def get_secure_cookie(self, name, value=None, max_age_days=31,\n                          min_version=None):\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        .. versionchanged:: 3.2.1\n\n           Added the ``min_version`` argument.  Introduced cookie version 2;\n           both versions 1 and 2 are accepted by default.\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                                   min_version=min_version)\n\n    def get_secure_cookie_key_version(self, name, value=None):\n        \"\"\"Returns the signing key version of the secure cookie.\n\n        The version is returned as int.\n        \"\"\"\n        self.require_setting(\"cookie_secret\", \"secure cookies\")\n        if value is None:\n            value = self.get_cookie(name)\n        return get_signature_key_version(value)\n\n    def redirect(self, url, permanent=False, status=None):\n        \"\"\"Sends a redirect to the given (optionally relative) URL.\n\n        If the ``status`` argument is specified, that value is used as the\n        HTTP status code; otherwise either 301 (permanent) or 302\n        (temporary) is chosen based on the ``permanent`` argument.\n        The default is 302 (temporary).\n        \"\"\"\n        if self._headers_written:\n            raise Exception(\"Cannot redirect after headers have been written\")\n        if status is None:\n            status = 301 if permanent else 302\n        else:\n            assert isinstance(status, int) and 300 <= status <= 399\n        self.set_status(status)\n        self.set_header(\"Location\", utf8(url))\n        self.finish()\n\n    def write(self, chunk):\n        \"\"\"Writes the given chunk to the output buffer.\n\n        To write the output to the network, use the flush() method below.\n\n        If the given chunk is a dictionary, we write it as JSON and set\n        the Content-Type of the response to be ``application/json``.\n        (if you want to send JSON as a different ``Content-Type``, call\n        set_header *after* calling write()).\n\n        Note that lists are not converted to JSON because of a potential\n        cross-site security vulnerability.  All JSON output should be\n        wrapped in a dictionary.  More details at\n        http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ and\n        https://github.com/facebook/tornado/issues/1009\n        \"\"\"\n        if self._finished:\n            raise RuntimeError(\"Cannot write() after finish()\")\n        if not isinstance(chunk, (bytes, unicode_type, dict)):\n            message = \"write() only accepts bytes, unicode, and dict objects\"\n            if isinstance(chunk, list):\n                message += \". Lists not accepted for security reasons; see http://www.tornadoweb.org/en/stable/web.html#tornado.web.RequestHandler.write\"\n            raise TypeError(message)\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)):\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)):\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            pgettext=self.locale.pgettext,\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`` and ``template_whitespace`` application\n        settings.  If a ``template_loader`` application setting is\n        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        if \"template_whitespace\" in settings:\n            kwargs[\"whitespace\"] = settings[\"template_whitespace\"]\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        .. versionchanged:: 4.0\n           Now returns a `.Future` if no callback is given.\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,\n                        chunk, include_footers)\n            # Ignore the chunk and only write the headers for HEAD requests\n            if self.request.method == \"HEAD\":\n                chunk = None\n\n            # Finalize the cookie headers (which have been stored in a side\n            # object so an outgoing cookie could be overwritten before it\n            # is sent).\n            if hasattr(self, \"_new_cookie\"):\n                for cookie in self._new_cookie.values():\n                    self.add_header(\"Set-Cookie\", cookie.OutputString(None))\n\n            start_line = httputil.ResponseStartLine('',\n                                                    self._status_code,\n                                                    self._reason)\n            return self.request.connection.write_headers(\n                start_line, self._headers, chunk, callback=callback)\n        else:\n            for transform in self._transforms:\n                chunk = transform.transform_chunk(chunk, include_footers)\n            # Ignore the chunk and only write the headers for HEAD requests\n            if self.request.method != \"HEAD\":\n                return self.request.connection.write(chunk, callback=callback)\n            else:\n                future = Future()\n                future.set_result(None)\n                return future\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\")\n\n        if chunk is not None:\n            self.write(chunk)\n\n        # Automatically support ETags and add the Content-Length header if\n        # we have not flushed any content yet.\n        if not self._headers_written:\n            if (self._status_code == 200 and\n                self.request.method in (\"GET\", \"HEAD\") and\n                    \"Etag\" not in self._headers):\n                self.set_etag_header()\n                if self.check_etag_header():\n                    self._write_buffer = []\n                    self.set_status(304)\n            if self._status_code == 304:\n                assert not self._write_buffer, \"Cannot send body with 304\"\n                self._clear_headers_for_304()\n            elif \"Content-Length\" not in self._headers:\n                content_length = sum(len(part) for part in self._write_buffer)\n                self.set_header(\"Content-Length\", content_length)\n\n        if hasattr(self.request, \"connection\"):\n            # Now that the request is finished, clear the callback we\n            # set on the HTTPConnection (which would otherwise prevent the\n            # garbage collection of the RequestHandler when there\n            # are keepalive connections)\n            self.request.connection.set_close_callback(None)\n\n        self.flush(include_footers=True)\n        self.request.finish()\n        self._log()\n        self._finished = True\n        self.on_finish()\n        # Break up a reference cycle between this handler and the\n        # _ui_module closures to allow for faster GC on CPython.\n        self.ui = None\n\n    def send_error(self, status_code=500, **kwargs):\n        \"\"\"Sends the given HTTP error code to the browser.\n\n        If `flush()` has already been called, it is not possible to send\n        an error, so this method will simply terminate the response.\n        If output has been written but not yet flushed, it will be discarded\n        and replaced with the error page.\n\n        Override `write_error()` to customize the error page that is returned.\n        Additional keyword arguments are passed through to `write_error`.\n        \"\"\"\n        if self._headers_written:\n            gen_log.error(\"Cannot send error response after headers written\")\n            if not self._finished:\n                # If we get an error between writing headers and finishing,\n                # we are unlikely to be able to finish due to a\n                # Content-Length mismatch. Try anyway to release the\n                # socket.\n                try:\n                    self.finish()\n                except Exception:\n                    gen_log.error(\"Failed to flush partial response\",\n                                  exc_info=True)\n            return\n        self.clear()\n\n        reason = kwargs.get('reason')\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        if self.settings.get(\"serve_traceback\") 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 locale 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        .. versionchanged: 4.1\n           Added a property setter.\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    @locale.setter\n    def locale(self, value):\n        self._locale = value\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 set in one of two ways:\n\n        * A subclass may override `get_current_user()`, which will be called\n          automatically the first time ``self.current_user`` is accessed.\n          `get_current_user()` will only be called once per request,\n          and is cached for future access::\n\n              def get_current_user(self):\n                  user_cookie = self.get_secure_cookie(\"user\")\n                      if user_cookie:\n                          return json.loads(user_cookie)\n                  return None\n\n        * It may be set as a normal variable, typically from an overridden\n          `prepare()`::\n\n              @gen.coroutine\n              def prepare(self):\n                  user_id_cookie = self.get_secure_cookie(\"user_id\")\n                  if user_id_cookie:\n                      self.current_user = yield load_user(user_id_cookie)\n\n        Note that `prepare()` may be a coroutine while `get_current_user()`\n        may not, so the latter form is necessary if loading the user requires\n        asynchronous operations.\n\n        The user object may any type of the application's choosing.\n        \"\"\"\n        if not hasattr(self, \"_current_user\"):\n            self._current_user = self.get_current_user()\n        return self._current_user\n\n    @current_user.setter\n    def current_user(self, value):\n        self._current_user = value\n\n    def get_current_user(self):\n        \"\"\"Override to determine the current user from, e.g., a cookie.\n\n        This method may not be a coroutine.\n        \"\"\"\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        .. versionchanged:: 3.2.2\n           The xsrf token will now be have a random mask applied in every\n           request, which makes it safe to include the token in pages\n           that are compressed.  See http://breachattack.com for more\n           information on the issue fixed by this change.  Old (version 1)\n           cookies will be converted to version 2 when this method is called\n           unless the ``xsrf_cookie_version`` `Application` setting is\n           set to 1.\n\n        .. versionchanged:: 4.3\n           The ``xsrf_cookie_kwargs`` `Application` setting may be\n           used to supply additional cookie options (which will be\n           passed directly to `set_cookie`). For example,\n           ``xsrf_cookie_kwargs=dict(httponly=True, secure=True)``\n           will set the ``secure`` and ``httponly`` flags on the\n           ``_xsrf`` cookie.\n        \"\"\"\n        if not hasattr(self, \"_xsrf_token\"):\n            version, token, timestamp = self._get_raw_xsrf_token()\n            output_version = self.settings.get(\"xsrf_cookie_version\", 2)\n            cookie_kwargs = self.settings.get(\"xsrf_cookie_kwargs\", {})\n            if output_version == 1:\n                self._xsrf_token = binascii.b2a_hex(token)\n            elif output_version == 2:\n                mask = os.urandom(4)\n                self._xsrf_token = b\"|\".join([\n                    b\"2\",\n                    binascii.b2a_hex(mask),\n                    binascii.b2a_hex(_websocket_mask(mask, token)),\n                    utf8(str(int(timestamp)))])\n            else:\n                raise ValueError(\"unknown xsrf cookie version %d\",\n                                 output_version)\n            if version is None:\n                expires_days = 30 if self.current_user else None\n                self.set_cookie(\"_xsrf\", self._xsrf_token,\n                                expires_days=expires_days,\n                                **cookie_kwargs)\n        return self._xsrf_token\n\n    def _get_raw_xsrf_token(self):\n        \"\"\"Read or generate the xsrf token in its raw form.\n\n        The raw_xsrf_token is a tuple containing:\n\n        * version: the version of the cookie from which this token was read,\n          or None if we generated a new token in this request.\n        * token: the raw token data; random (non-ascii) bytes.\n        * timestamp: the time this token was generated (will not be accurate\n          for version 1 cookies)\n        \"\"\"\n        if not hasattr(self, '_raw_xsrf_token'):\n            cookie = self.get_cookie(\"_xsrf\")\n            if cookie:\n                version, token, timestamp = self._decode_xsrf_token(cookie)\n            else:\n                version, token, timestamp = None, None, None\n            if token is None:\n                version = None\n                token = os.urandom(16)\n                timestamp = time.time()\n            self._raw_xsrf_token = (version, token, timestamp)\n        return self._raw_xsrf_token\n\n    def _decode_xsrf_token(self, cookie):\n        \"\"\"Convert a cookie string into a the tuple form returned by\n        _get_raw_xsrf_token.\n        \"\"\"\n\n        try:\n            m = _signed_value_version_re.match(utf8(cookie))\n\n            if m:\n                version = int(m.group(1))\n                if version == 2:\n                    _, mask, masked_token, timestamp = cookie.split(\"|\")\n\n                    mask = binascii.a2b_hex(utf8(mask))\n                    token = _websocket_mask(\n                        mask, binascii.a2b_hex(utf8(masked_token)))\n                    timestamp = int(timestamp)\n                    return version, token, timestamp\n                else:\n                    # Treat unknown versions as not present instead of failing.\n                    raise Exception(\"Unknown xsrf cookie version\")\n            else:\n                version = 1\n                try:\n                    token = binascii.a2b_hex(utf8(cookie))\n                except (binascii.Error, TypeError):\n                    token = utf8(cookie)\n                # We don't have a usable timestamp in older versions.\n                timestamp = int(time.time())\n                return (version, token, timestamp)\n        except Exception:\n            # Catch exceptions and return nothing instead of failing.\n            gen_log.debug(\"Uncaught exception in _decode_xsrf_token\",\n                          exc_info=True)\n            return None, None, None\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        .. versionchanged:: 3.2.2\n           Added support for cookie version 2.  Both versions 1 and 2 are\n           supported.\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        _, token, _ = self._decode_xsrf_token(token)\n        _, expected_token, _ = self._get_raw_xsrf_token()\n        if not _time_independent_equals(utf8(token), utf8(expected_token)):\n            raise HTTPError(403, \"XSRF cookie does not match POST argument\")\n\n    def xsrf_form_html(self):\n        \"\"\"An HTML ``<input/>`` element to be included with all POST forms.\n\n        It defines the ``_xsrf`` input value, which we check on all POST\n        requests to prevent cross-site request forgery. If you have set\n        the ``xsrf_cookies`` application setting, you must include this\n        HTML within all of your HTML forms.\n\n        In a template, this method should be called with ``{% module\n        xsrf_form_html() %}``\n\n        See `check_xsrf_cookie()` above for more information.\n        \"\"\"\n        return '<input type=\"hidden\" name=\"_xsrf\" value=\"' + \\\n            escape.xhtml_escape(self.xsrf_token) + '\"/>'\n\n    def static_url(self, path, include_host=None, **kwargs):\n        \"\"\"Returns a static URL for the given relative static file path.\n\n        This method requires you set the ``static_path`` setting in your\n        application (which specifies the root directory of your static\n        files).\n\n        This method returns a versioned url (by default appending\n        ``?v=<signature>``), which allows the static files to be\n        cached indefinitely.  This can be disabled by passing\n        ``include_version=False`` (in the default implementation;\n        other static file implementations are not required to support\n        this, but they may support other options).\n\n        By default this method returns URLs relative to the current\n        host, but if ``include_host`` is true the URL returned will be\n        absolute.  If this handler has an ``include_host`` attribute,\n        that value will be used as the default for all `static_url`\n        calls that do not pass ``include_host`` as a keyword argument.\n\n        \"\"\"\n        self.require_setting(\"static_path\", \"static_url\")\n        get_url = self.settings.get(\"static_handler_class\",\n                                    StaticFileHandler).make_static_url\n\n        if include_host is None:\n            include_host = getattr(self, \"include_host\", False)\n\n        if include_host:\n            base = self.request.protocol + \"://\" + self.request.host\n        else:\n            base = \"\"\n\n        return base + get_url(self.settings, path, **kwargs)\n\n    def require_setting(self, name, feature=\"this feature\"):\n        \"\"\"Raises an exception if the given app setting is not defined.\"\"\"\n        if not self.application.settings.get(name):\n            raise Exception(\"You must define the '%s' setting in your \"\n                            \"application to use %s\" % (name, feature))\n\n    def reverse_url(self, name, *args):\n        \"\"\"Alias for `Application.reverse_url`.\"\"\"\n        return self.application.reverse_url(name, *args)\n\n    def compute_etag(self):\n        \"\"\"Computes the etag header to be used for this request.\n\n        By default uses a hash of the content written so far.\n\n        May be overridden to provide custom etag implementations,\n        or may return None to disable tornado's default etag support.\n        \"\"\"\n        hasher = hashlib.sha1()\n        for part in self._write_buffer:\n            hasher.update(part)\n        return '\"%s\"' % hasher.hexdigest()\n\n    def set_etag_header(self):\n        \"\"\"Sets the response's Etag header using ``self.compute_etag()``.\n\n        Note: no header will be set if ``compute_etag()`` returns ``None``.\n\n        This method is called automatically when the request is finished.\n        \"\"\"\n        etag = self.compute_etag()\n        if etag is not None:\n            self.set_header(\"Etag\", etag)\n\n    def check_etag_header(self):\n        \"\"\"Checks the ``Etag`` header against requests's ``If-None-Match``.\n\n        Returns ``True`` if the request's Etag matches and a 304 should be\n        returned. For example::\n\n            self.set_etag_header()\n            if self.check_etag_header():\n                self.set_status(304)\n                return\n\n        This method is called automatically when the request is finished,\n        but may be called earlier for applications that override\n        `compute_etag` and want to do an early check for ``If-None-Match``\n        before completing the request.  The ``Etag`` header should be set\n        (perhaps with `set_etag_header`) before calling this method.\n        \"\"\"\n        computed_etag = utf8(self._headers.get(\"Etag\", \"\"))\n        # Find all weak and strong etag values from If-None-Match header\n        # because RFC 7232 allows multiple etag values in a single header.\n        etags = re.findall(\n            br'\\*|(?:W/)?\"[^\"]*\"',\n            utf8(self.request.headers.get(\"If-None-Match\", \"\"))\n        )\n        if not computed_etag or not etags:\n            return False\n\n        match = False\n        if etags[0] == b'*':\n            match = True\n        else:\n            # Use a weak comparison when comparing entity-tags.\n            val = lambda x: x[2:] if x.startswith(b'W/') else x\n            for etag in etags:\n                if val(etag) == val(computed_etag):\n                    match = True\n                    break\n        return match\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    @gen.coroutine\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\n            result = self.prepare()\n            if result is not None:\n                result = yield result\n            if self._prepared_future is not None:\n                # Tell the Application we've finished with prepare()\n                # and are ready for the body to arrive.\n                self._prepared_future.set_result(None)\n            if self._finished:\n                return\n\n            if _has_stream_request_body(self.__class__):\n                # In streaming mode request.body is a Future that signals\n                # the body has been completely received.  The Future has no\n                # result; the data has been passed to self.data_received\n                # instead.\n                try:\n                    yield self.request.body\n                except iostream.StreamClosedError:\n                    return\n\n            method = getattr(self, self.request.method.lower())\n            result = method(*self.path_args, **self.path_kwargs)\n            if result is not None:\n                result = yield result\n            if self._auto_finish and not self._finished:\n                self.finish()\n        except Exception as e:\n            try:\n                self._handle_request_exception(e)\n            except Exception:\n                app_log.error(\"Exception in exception handler\", exc_info=True)\n            if (self._prepared_future is not None and\n                    not self._prepared_future.done()):\n                # In case we failed before setting _prepared_future, do it\n                # now (to unblock the HTTP server).  Note that this is not\n                # in a finally block to avoid GC issues prior to Python 3.4.\n                self._prepared_future.set_result(None)\n\n    def data_received(self, chunk):\n        \"\"\"Implement this method to handle streamed request data.\n\n        Requires the `.stream_request_body` decorator.\n        \"\"\"\n        raise NotImplementedError()\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 \"%s %s (%s)\" % (self.request.method, self.request.uri,\n                               self.request.remote_ip)\n\n    def _handle_request_exception(self, e):\n        if isinstance(e, Finish):\n            # Not an error; just finish the request without logging.\n            if not self._finished:\n                self.finish(*e.args)\n            return\n        try:\n            self.log_exception(*sys.exc_info())\n        except Exception:\n            # An error here should still get a best-effort send_error()\n            # to avoid leaking the connection.\n            app_log.error(\"Error in exception logger\", exc_info=True)\n        if self._finished:\n            # Extra errors after the request has been finished should\n            # be logged, but there is no reason to continue to try and\n            # send a response.\n            return\n        if isinstance(e, HTTPError):\n            if e.status_code not in httputil.responses and not e.reason:\n                gen_log.error(\"Bad HTTP status code: %d\", e.status_code)\n                self.send_error(500, exc_info=sys.exc_info())\n            else:\n                self.send_error(e.status_code, exc_info=sys.exc_info())\n        else:\n            self.send_error(500, exc_info=sys.exc_info())\n\n    def log_exception(self, typ, value, tb):\n        \"\"\"Override to customize logging of uncaught exceptions.\n\n        By default logs instances of `HTTPError` as warnings without\n        stack traces (on the ``tornado.general`` logger), and all\n        other exceptions as errors with stack traces (on the\n        ``tornado.application`` logger).\n\n        .. versionadded:: 3.1\n        \"\"\"\n        if isinstance(value, HTTPError):\n            if value.log_message:\n                format = \"%d %s: \" + value.log_message\n                args = ([value.status_code, self._request_summary()] +\n                        list(value.args))\n                gen_log.warning(format, *args)\n        else:\n            app_log.error(\"Uncaught exception %s\\n%r\", self._request_summary(),\n                          self.request, exc_info=(typ, value, tb))\n\n    def _ui_module(self, name, module):\n        def render(*args, **kwargs):\n            if not hasattr(self, \"_active_modules\"):\n                self._active_modules = {}\n            if name not in self._active_modules:\n                self._active_modules[name] = module(self)\n            rendered = self._active_modules[name].render(*args, **kwargs)\n            return rendered\n        return render\n\n    def _ui_method(self, method):\n        return lambda *args, **kwargs: method(self, *args, **kwargs)\n\n    def _clear_headers_for_304(self):\n        # 304 responses should not contain entity headers (defined in\n        # http://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html#sec7.1)\n        # not explicitly allowed by\n        # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5\n        headers = [\"Allow\", \"Content-Encoding\", \"Content-Language\",\n                   \"Content-Length\", \"Content-MD5\", \"Content-Range\",\n                   \"Content-Type\", \"Last-Modified\"]\n        for h in headers:\n            self.clear_header(h)\n\n\ndef asynchronous(method):\n    \"\"\"Wrap request handler methods with this if they are asynchronous.\n\n    This decorator is for callback-style asynchronous methods; for\n    coroutines, use the ``@gen.coroutine`` decorator without\n    ``@asynchronous``. (It is legal for legacy reasons to use the two\n    decorators together provided ``@asynchronous`` is first, but\n    ``@asynchronous`` will be ignored in this case)\n\n    This decorator should only be applied to the :ref:`HTTP verb\n    methods <verbs>`; its behavior is undefined for any other method.\n    This decorator does not *make* a method asynchronous; it tells\n    the framework that the method *is* asynchronous.  For this decorator\n    to be useful the method must (at least sometimes) do something\n    asynchronous.\n\n    If this decorator is given, the response is not finished when the\n    method returns. It is up to the request handler to call\n    `self.finish() <RequestHandler.finish>` to finish the HTTP\n    request. Without this decorator, the request is automatically\n    finished when the ``get()`` or ``post()`` method returns. Example:\n\n    .. testcode::\n\n       class MyRequestHandler(RequestHandler):\n           @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    .. testoutput::\n       :hide:\n\n    .. versionchanged:: 3.1\n       The ability to use ``@gen.coroutine`` without ``@asynchronous``.\n\n    .. versionchanged:: 4.3 Returning anything but ``None`` or a\n       yieldable object from a method decorated with ``@asynchronous``\n       is an error. Such return values were previously ignored silently.\n    \"\"\"\n    # Delay the IOLoop import because it's not available on app engine.\n    from tornado.ioloop import IOLoop\n\n    @functools.wraps(method)\n    def wrapper(self, *args, **kwargs):\n        self._auto_finish = False\n        with stack_context.ExceptionStackContext(\n                self._stack_context_handle_exception):\n            result = method(self, *args, **kwargs)\n            if result is not None:\n                result = gen.convert_yielded(result)\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                # Once we have done this, hide the Future from our\n                # caller (i.e. RequestHandler._when_complete), which\n                # would otherwise set up its own callback and\n                # exception handler (resulting in exceptions being\n                # logged twice).\n                return None\n            return result\n    return wrapper\n\n\ndef stream_request_body(cls):\n    \"\"\"Apply to `RequestHandler` subclasses to enable streaming body support.\n\n    This decorator implies the following changes:\n\n    * `.HTTPServerRequest.body` is undefined, and body arguments will not\n      be included in `RequestHandler.get_argument`.\n    * `RequestHandler.prepare` is called when the request headers have been\n      read instead of after the entire body has been read.\n    * The subclass must define a method ``data_received(self, data):``, which\n      will be called zero or more times as data is available.  Note that\n      if the request has an empty body, ``data_received`` may not be called.\n    * ``prepare`` and ``data_received`` may return Futures (such as via\n      ``@gen.coroutine``, in which case the next method will not be called\n      until those futures have completed.\n    * The regular HTTP method (``post``, ``put``, etc) will be called after\n      the entire body has been read.\n\n    There is a subtle interaction between ``data_received`` and asynchronous\n    ``prepare``: The first call to ``data_received`` may occur at any point\n    after the call to ``prepare`` has returned *or yielded*.\n    \"\"\"\n    if not issubclass(cls, RequestHandler):\n        raise TypeError(\"expected subclass of RequestHandler, got %r\", cls)\n    cls._stream_request_body = True\n    return cls\n\n\ndef _has_stream_request_body(cls):\n    if not issubclass(cls, RequestHandler):\n        raise TypeError(\"expected subclass of RequestHandler, got %r\", cls)\n    return getattr(cls, '_stream_request_body', False)\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(httputil.HTTPServerConnectionDelegate):\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.current().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    The request class can be specified as either a class object or a\n    (fully-qualified) name.\n\n    Each tuple can contain additional elements, which correspond to the\n    arguments to the `URLSpec` constructor.  (Prior to Tornado 3.2,\n    only tuples of two or three elements were allowed).\n\n    A dictionary may be passed as the third element of the tuple,\n    which will be used as keyword arguments to the handler's\n    constructor and `~RequestHandler.initialize` method.  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    \"\"\"\n    def __init__(self, handlers=None, default_host=\"\", transforms=None,\n                 **settings):\n        if transforms is None:\n            self.transforms = []\n            if settings.get(\"compress_response\") or settings.get(\"gzip\"):\n                self.transforms.append(GZipContentEncoding)\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._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        if self.settings.get('debug'):\n            self.settings.setdefault('autoreload', True)\n            self.settings.setdefault('compiled_template_cache', False)\n            self.settings.setdefault('static_hash_cache', False)\n            self.settings.setdefault('serve_traceback', True)\n\n        # Automatically reload modified modules\n        if self.settings.get('autoreload'):\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.current().start()`` to start the server.\n\n        Returns the `.HTTPServer` object.\n\n        .. versionchanged:: 4.3\n           Now returns the `.HTTPServer` object.\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        return server\n\n    def add_handlers(self, host_pattern, host_handlers):\n        \"\"\"Appends the given handlers to our handler list.\n\n        Host patterns are processed sequentially in the order they were\n        added. All matching patterns will be considered.\n        \"\"\"\n        if not host_pattern.endswith(\"$\"):\n            host_pattern += \"$\"\n        handlers = []\n        # The handlers with the wildcard host_pattern are a special\n        # case - they're added in the constructor but should have lower\n        # precedence than the more-precise handlers added later.\n        # If a wildcard handler group exists, it should always be last\n        # in the list, so insert new groups just before it.\n        if self.handlers and self.handlers[-1][0].pattern == '.*$':\n            self.handlers.insert(-1, (re.compile(host_pattern), handlers))\n        else:\n            self.handlers.append((re.compile(host_pattern), handlers))\n\n        for spec in host_handlers:\n            if isinstance(spec, (tuple, list)):\n                assert len(spec) in (2, 3, 4)\n                spec = URLSpec(*spec)\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 = split_host_and_port(request.host.lower())[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 start_request(self, server_conn, request_conn):\n        # Modern HTTPServer interface\n        return _RequestDispatcher(self, request_conn)\n\n    def __call__(self, request):\n        # Legacy HTTPServer interface\n        dispatcher = _RequestDispatcher(self, None)\n        dispatcher.set_request(request)\n        return dispatcher.execute()\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 _RequestDispatcher(httputil.HTTPMessageDelegate):\n    def __init__(self, application, connection):\n        self.application = application\n        self.connection = connection\n        self.request = None\n        self.chunks = []\n        self.handler_class = None\n        self.handler_kwargs = None\n        self.path_args = []\n        self.path_kwargs = {}\n\n    def headers_received(self, start_line, headers):\n        self.set_request(httputil.HTTPServerRequest(\n            connection=self.connection, start_line=start_line,\n            headers=headers))\n        if self.stream_request_body:\n            self.request.body = Future()\n            return self.execute()\n\n    def set_request(self, request):\n        self.request = request\n        self._find_handler()\n        self.stream_request_body = _has_stream_request_body(self.handler_class)\n\n    def _find_handler(self):\n        # Identify the handler to use as soon as we have the request.\n        # Save url path arguments for later.\n        app = self.application\n        handlers = app._get_host_handlers(self.request)\n        if not handlers:\n            self.handler_class = RedirectHandler\n            self.handler_kwargs = dict(url=\"%s://%s/\"\n                                       % (self.request.protocol,\n                                          app.default_host))\n            return\n        for spec in handlers:\n            match = spec.regex.match(self.request.path)\n            if match:\n                self.handler_class = spec.handler_class\n                self.handler_kwargs = spec.kwargs\n                if spec.regex.groups:\n                    # Pass matched groups to the handler.  Since\n                    # match.groups() includes both named and\n                    # unnamed groups, we want to use either groups\n                    # or groupdict but not both.\n                    if spec.regex.groupindex:\n                        self.path_kwargs = dict(\n                            (str(k), _unquote_or_none(v))\n                            for (k, v) in match.groupdict().items())\n                    else:\n                        self.path_args = [_unquote_or_none(s)\n                                          for s in match.groups()]\n                return\n        if app.settings.get('default_handler_class'):\n            self.handler_class = app.settings['default_handler_class']\n            self.handler_kwargs = app.settings.get(\n                'default_handler_args', {})\n        else:\n            self.handler_class = ErrorHandler\n            self.handler_kwargs = dict(status_code=404)\n\n    def data_received(self, data):\n        if self.stream_request_body:\n            return self.handler.data_received(data)\n        else:\n            self.chunks.append(data)\n\n    def finish(self):\n        if self.stream_request_body:\n            self.request.body.set_result(None)\n        else:\n            self.request.body = b''.join(self.chunks)\n            self.request._parse_body()\n            self.execute()\n\n    def on_connection_close(self):\n        if self.stream_request_body:\n            self.handler.on_connection_close()\n        else:\n            self.chunks = None\n\n    def execute(self):\n        # If template cache is disabled (usually in the debug mode),\n        # re-compile templates and reload static files on every\n        # request so you don't need to restart to see changes\n        if not self.application.settings.get(\"compiled_template_cache\", True):\n            with RequestHandler._template_loader_lock:\n                for loader in RequestHandler._template_loaders.values():\n                    loader.reset()\n        if not self.application.settings.get('static_hash_cache', True):\n            StaticFileHandler.reset()\n\n        self.handler = self.handler_class(self.application, self.request,\n                                          **self.handler_kwargs)\n        transforms = [t(self.request) for t in self.application.transforms]\n\n        if self.stream_request_body:\n            self.handler._prepared_future = Future()\n        # Note that if an exception escapes handler._execute it will be\n        # trapped in the Future it returns (which we are ignoring here,\n        # leaving it to be logged when the Future is GC'd).\n        # However, that shouldn't happen because _execute has a blanket\n        # except handler, and we cannot easily access the IOLoop here to\n        # call add_future (because of the requirement to remain compatible\n        # with WSGI)\n        self.handler._execute(transforms, *self.path_args,\n                              **self.path_kwargs)\n        # If we are streaming the request body, then execute() is finished\n        # when the handler has prepared to receive the body.  If not,\n        # it doesn't matter when execute() finishes (so we return None)\n        return self.handler._prepared_future\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    To customize the response sent with an `HTTPError`, override\n    `RequestHandler.write_error`.\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=500, 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        if log_message and not args:\n            self.log_message = log_message.replace('%', '%%')\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 Finish(Exception):\n    \"\"\"An exception that ends the request without producing an error response.\n\n    When `Finish` is raised in a `RequestHandler`, the request will\n    end (calling `RequestHandler.finish` if it hasn't already been\n    called), but the error-handling methods (including\n    `RequestHandler.write_error`) will not be called.\n\n    If `Finish()` was created with no arguments, the pending response\n    will be sent as-is. If `Finish()` was given an argument, that\n    argument will be passed to `RequestHandler.finish()`.\n\n    This can be a more convenient way to implement custom error pages\n    than overriding ``write_error`` (especially in library code)::\n\n        if self.current_user is None:\n            self.set_status(401)\n            self.set_header('WWW-Authenticate', 'Basic realm=\"something\"')\n            raise Finish()\n\n    .. versionchanged:: 4.3\n       Arguments passed to ``Finish()`` will be passed on to\n       `RequestHandler.finish`.\n    \"\"\"\n    pass\n\n\nclass MissingArgumentError(HTTPError):\n    \"\"\"Exception raised by `RequestHandler.get_argument`.\n\n    This is a subclass of `HTTPError`, so if it is uncaught a 400 response\n    code will be used instead of 500 (and a stack trace will not be logged).\n\n    .. versionadded:: 3.1\n    \"\"\"\n    def __init__(self, arg_name):\n        super(MissingArgumentError, self).__init__(\n            400, 'Missing argument %s' % arg_name)\n        self.arg_name = arg_name\n\n\nclass ErrorHandler(RequestHandler):\n    \"\"\"Generates an error response with ``status_code`` for all requests.\"\"\"\n    def initialize(self, status_code):\n        self.set_status(status_code)\n\n    def prepare(self):\n        raise HTTPError(self._status_code)\n\n    def check_xsrf_cookie(self):\n        # POSTs to an ErrorHandler don't actually have side effects,\n        # so we don't need to check the xsrf token.  This allows POSTs\n        # to the wrong url to return a 404 instead of 403.\n        pass\n\n\nclass RedirectHandler(RequestHandler):\n    \"\"\"Redirects the client to the given URL for all GET requests.\n\n    You should provide the keyword argument ``url`` to the handler, e.g.::\n\n        application = web.Application([\n            (r\"/oldpath\", web.RedirectHandler, {\"url\": \"/newpath\"}),\n        ])\n    \"\"\"\n    def initialize(self, url, permanent=True):\n        self._url = url\n        self._permanent = permanent\n\n    def get(self):\n        self.redirect(self._url, permanent=self._permanent)\n\n\nclass StaticFileHandler(RequestHandler):\n    \"\"\"A simple handler that can serve static content from a directory.\n\n    A `StaticFileHandler` is configured automatically if you pass the\n    ``static_path`` keyword argument to `Application`.  This handler\n    can be customized with the ``static_url_prefix``, ``static_handler_class``,\n    and ``static_handler_args`` settings.\n\n    To map an additional path to this handler for a static data directory\n    you would add a line to your application like::\n\n        application = web.Application([\n            (r\"/content/(.*)\", web.StaticFileHandler, {\"path\": \"/var/www\"}),\n        ])\n\n    The handler constructor requires a ``path`` argument, which specifies the\n    local root directory of the content to be served.\n\n    Note that a capture group in the regex is required to parse the value for\n    the ``path`` argument to the get() method (different than the constructor\n    argument above); see `URLSpec` for details.\n\n    To serve a file like ``index.html`` automatically when a directory is\n    requested, set ``static_handler_args=dict(default_filename=\"index.html\")``\n    in your application settings, or add ``default_filename`` as an initializer\n    argument for your ``StaticFileHandler``.\n\n    To maximize the effectiveness of browser caching, this class supports\n    versioned urls (by default using the argument ``?v=``).  If a version\n    is given, we instruct the browser to cache this file indefinitely.\n    `make_static_url` (also available as `RequestHandler.static_url`) can\n    be used to construct a versioned url.\n\n    This handler is intended primarily for use in development and light-duty\n    file serving; for heavy traffic it will be more efficient to use\n    a dedicated static file server (such as nginx or Apache).  We support\n    the HTTP ``Accept-Ranges`` mechanism to return partial content (because\n    some browsers require this functionality to be present to seek in\n    HTML5 audio or video).\n\n    **Subclassing notes**\n\n    This class is designed to be extensible by subclassing, but because\n    of the way static urls are generated with class methods rather than\n    instance methods, the inheritance patterns are somewhat unusual.\n    Be sure to use the ``@classmethod`` decorator when overriding a\n    class method.  Instance methods may use the attributes ``self.path``\n    ``self.absolute_path``, and ``self.modified``.\n\n    Subclasses should only override methods discussed in this section;\n    overriding other methods is error-prone.  Overriding\n    ``StaticFileHandler.get`` is particularly problematic due to the\n    tight coupling with ``compute_etag`` and other methods.\n\n    To change the way static urls are generated (e.g. to match the behavior\n    of another server or CDN), override `make_static_url`, `parse_url_path`,\n    `get_cache_time`, and/or `get_version`.\n\n    To replace all interaction with the filesystem (e.g. to serve\n    static content from a database), override `get_content`,\n    `get_content_size`, `get_modified_time`, `get_absolute_path`, and\n    `validate_absolute_path`.\n\n    .. versionchanged:: 3.1\n       Many of the methods for subclasses were added in Tornado 3.1.\n    \"\"\"\n    CACHE_MAX_AGE = 86400 * 365 * 10  # 10 years\n\n    _static_hashes = {}\n    _lock = threading.Lock()  # protects _static_hashes\n\n    def initialize(self, path, default_filename=None):\n        self.root = path\n        self.default_filename = default_filename\n\n    @classmethod\n    def reset(cls):\n        with cls._lock:\n            cls._static_hashes = {}\n\n    def head(self, path):\n        return self.get(path, include_body=False)\n\n    @gen.coroutine\n    def get(self, path, include_body=True):\n        # Set up our path instance variables.\n        self.path = self.parse_url_path(path)\n        del path  # make sure we don't refer to path instead of self.path again\n        absolute_path = self.get_absolute_path(self.root, self.path)\n        self.absolute_path = self.validate_absolute_path(\n            self.root, absolute_path)\n        if self.absolute_path is None:\n            return\n\n        self.modified = self.get_modified_time()\n        self.set_headers()\n\n        if self.should_return_304():\n            self.set_status(304)\n            return\n\n        request_range = None\n        range_header = self.request.headers.get(\"Range\")\n        if range_header:\n            # As per RFC 2616 14.16, if an invalid Range header is specified,\n            # the request will be treated as if the header didn't exist.\n            request_range = httputil._parse_request_range(range_header)\n\n        size = self.get_content_size()\n        if request_range:\n            start, end = request_range\n            if (start is not None and start >= size) or end == 0:\n                # As per RFC 2616 14.35.1, a range is not satisfiable only: if\n                # the first requested byte is equal to or greater than the\n                # content, or when a suffix with length 0 is specified\n                self.set_status(416)  # Range Not Satisfiable\n                self.set_header(\"Content-Type\", \"text/plain\")\n                self.set_header(\"Content-Range\", \"bytes */%s\" % (size, ))\n                return\n            if start is not None and start < 0:\n                start += size\n            if end is not None and end > size:\n                # Clients sometimes blindly use a large range to limit their\n                # download size; cap the endpoint at the actual file size.\n                end = size\n            # Note: only return HTTP 206 if less than the entire range has been\n            # requested. Not only is this semantically correct, but Chrome\n            # refuses to play audio if it gets an HTTP 206 in response to\n            # ``Range: bytes=0-``.\n            if size != (end or size) - (start or 0):\n                self.set_status(206)  # Partial Content\n                self.set_header(\"Content-Range\",\n                                httputil._get_content_range(start, end, size))\n        else:\n            start = end = None\n\n        if start is not None and end is not None:\n            content_length = end - start\n        elif end is not None:\n            content_length = end\n        elif start is not None:\n            content_length = size - start\n        else:\n            content_length = size\n        self.set_header(\"Content-Length\", content_length)\n\n        if include_body:\n            content = self.get_content(self.absolute_path, start, end)\n            if isinstance(content, bytes):\n                content = [content]\n            for chunk in content:\n                try:\n                    self.write(chunk)\n                    yield self.flush()\n                except iostream.StreamClosedError:\n                    return\n        else:\n            assert self.request.method == \"HEAD\"\n\n    def compute_etag(self):\n        \"\"\"Sets the ``Etag`` header based on static url version.\n\n        This allows efficient ``If-None-Match`` checks against cached\n        versions, and sends the correct ``Etag`` for a partial response\n        (i.e. the same ``Etag`` as the full file).\n\n        .. versionadded:: 3.1\n        \"\"\"\n        version_hash = self._get_cached_version(self.absolute_path)\n        if not version_hash:\n            return None\n        return '\"%s\"' % (version_hash, )\n\n    def set_headers(self):\n        \"\"\"Sets the content and caching headers on the response.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        self.set_header(\"Accept-Ranges\", \"bytes\")\n        self.set_etag_header()\n\n        if self.modified is not None:\n            self.set_header(\"Last-Modified\", self.modified)\n\n        content_type = self.get_content_type()\n        if content_type:\n            self.set_header(\"Content-Type\", content_type)\n\n        cache_time = self.get_cache_time(self.path, self.modified,\n                                         content_type)\n        if cache_time > 0:\n            self.set_header(\"Expires\", datetime.datetime.utcnow() +\n                            datetime.timedelta(seconds=cache_time))\n            self.set_header(\"Cache-Control\", \"max-age=\" + str(cache_time))\n\n        self.set_extra_headers(self.path)\n\n    def should_return_304(self):\n        \"\"\"Returns True if the headers indicate that we should return 304.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        if self.check_etag_header():\n            return True\n\n        # Check the If-Modified-Since, and don't send the result if the\n        # content has not been modified\n        ims_value = self.request.headers.get(\"If-Modified-Since\")\n        if ims_value is not None:\n            date_tuple = email.utils.parsedate(ims_value)\n            if date_tuple is not None:\n                if_since = datetime.datetime(*date_tuple[:6])\n                if if_since >= self.modified:\n                    return True\n\n        return False\n\n    @classmethod\n    def get_absolute_path(cls, root, path):\n        \"\"\"Returns the absolute location of ``path`` relative to ``root``.\n\n        ``root`` is the path configured for this `StaticFileHandler`\n        (in most cases the ``static_path`` `Application` setting).\n\n        This class method may be overridden in subclasses.  By default\n        it returns a filesystem path, but other strings may be used\n        as long as they are unique and understood by the subclass's\n        overridden `get_content`.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        abspath = os.path.abspath(os.path.join(root, path))\n        return abspath\n\n    def validate_absolute_path(self, root, absolute_path):\n        \"\"\"Validate and return the absolute path.\n\n        ``root`` is the configured path for the `StaticFileHandler`,\n        and ``path`` is the result of `get_absolute_path`\n\n        This is an instance method called during request processing,\n        so it may raise `HTTPError` or use methods like\n        `RequestHandler.redirect` (return None after redirecting to\n        halt further processing).  This is where 404 errors for missing files\n        are generated.\n\n        This method may modify the path before returning it, but note that\n        any such modifications will not be understood by `make_static_url`.\n\n        In instance methods, this method's result is available as\n        ``self.absolute_path``.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        # os.path.abspath strips a trailing /.\n        # We must add it back to `root` so that we only match files\n        # in a directory named `root` instead of files starting with\n        # that prefix.\n        root = os.path.abspath(root)\n        if not root.endswith(os.path.sep):\n            # abspath always removes a trailing slash, except when\n            # root is '/'. This is an unusual case, but several projects\n            # have independently discovered this technique to disable\n            # Tornado's path validation and (hopefully) do their own,\n            # so we need to support it.\n            root += os.path.sep\n        # The trailing slash also needs to be temporarily added back\n        # the requested path so a request to root/ will match.\n        if not (absolute_path + os.path.sep).startswith(root):\n            raise HTTPError(403, \"%s is not in root static directory\",\n                            self.path)\n        if (os.path.isdir(absolute_path) and\n                self.default_filename is not None):\n            # need to look at the request.path here for when path is empty\n            # but there is some prefix to the path that was already\n            # trimmed by the routing\n            if not self.request.path.endswith(\"/\"):\n                self.redirect(self.request.path + \"/\", permanent=True)\n                return\n            absolute_path = os.path.join(absolute_path, self.default_filename)\n        if not os.path.exists(absolute_path):\n            raise HTTPError(404)\n        if not os.path.isfile(absolute_path):\n            raise HTTPError(403, \"%s is not a file\", self.path)\n        return absolute_path\n\n    @classmethod\n    def get_content(cls, abspath, start=None, end=None):\n        \"\"\"Retrieve the content of the requested resource which is located\n        at the given absolute path.\n\n        This class method may be overridden by subclasses.  Note that its\n        signature is different from other overridable class methods\n        (no ``settings`` argument); this is deliberate to ensure that\n        ``abspath`` is able to stand on its own as a cache key.\n\n        This method should either return a byte string or an iterator\n        of byte strings.  The latter is preferred for large files\n        as it helps reduce memory fragmentation.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        with open(abspath, \"rb\") as file:\n            if start is not None:\n                file.seek(start)\n            if end is not None:\n                remaining = end - (start or 0)\n            else:\n                remaining = None\n            while True:\n                chunk_size = 64 * 1024\n                if remaining is not None and remaining < chunk_size:\n                    chunk_size = remaining\n                chunk = file.read(chunk_size)\n                if chunk:\n                    if remaining is not None:\n                        remaining -= len(chunk)\n                    yield chunk\n                else:\n                    if remaining is not None:\n                        assert remaining == 0\n                    return\n\n    @classmethod\n    def get_content_version(cls, abspath):\n        \"\"\"Returns a version string for the resource at the given path.\n\n        This class method may be overridden by subclasses.  The\n        default implementation is a hash of the file's contents.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        data = cls.get_content(abspath)\n        hasher = hashlib.md5()\n        if isinstance(data, bytes):\n            hasher.update(data)\n        else:\n            for chunk in data:\n                hasher.update(chunk)\n        return hasher.hexdigest()\n\n    def _stat(self):\n        if not hasattr(self, '_stat_result'):\n            self._stat_result = os.stat(self.absolute_path)\n        return self._stat_result\n\n    def get_content_size(self):\n        \"\"\"Retrieve the total size of the resource at the given path.\n\n        This method may be overridden by subclasses.\n\n        .. versionadded:: 3.1\n\n        .. versionchanged:: 4.0\n           This method is now always called, instead of only when\n           partial results are requested.\n        \"\"\"\n        stat_result = self._stat()\n        return stat_result[stat.ST_SIZE]\n\n    def get_modified_time(self):\n        \"\"\"Returns the time that ``self.absolute_path`` was last modified.\n\n        May be overridden in subclasses.  Should return a `~datetime.datetime`\n        object or None.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        stat_result = self._stat()\n        modified = datetime.datetime.utcfromtimestamp(\n            stat_result[stat.ST_MTIME])\n        return modified\n\n    def get_content_type(self):\n        \"\"\"Returns the ``Content-Type`` header to be used for this request.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        mime_type, encoding = mimetypes.guess_type(self.absolute_path)\n        # per RFC 6713, use the appropriate type for a gzip compressed file\n        if encoding == \"gzip\":\n            return \"application/gzip\"\n        # As of 2015-07-21 there is no bzip2 encoding defined at\n        # http://www.iana.org/assignments/media-types/media-types.xhtml\n        # So for that (and any other encoding), use octet-stream.\n        elif encoding is not None:\n            return \"application/octet-stream\"\n        elif mime_type is not None:\n            return mime_type\n        # if mime_type not detected, use application/octet-stream\n        else:\n            return \"application/octet-stream\"\n\n    def set_extra_headers(self, path):\n        \"\"\"For subclass to add extra headers to the response\"\"\"\n        pass\n\n    def get_cache_time(self, path, modified, mime_type):\n        \"\"\"Override to customize cache control behavior.\n\n        Return a positive number of seconds to make the result\n        cacheable for that amount of time or 0 to mark resource as\n        cacheable for an unspecified amount of time (subject to\n        browser heuristics).\n\n        By default returns cache expiry of 10 years for resources requested\n        with ``v`` argument.\n        \"\"\"\n        return self.CACHE_MAX_AGE if \"v\" in self.request.arguments else 0\n\n    @classmethod\n    def make_static_url(cls, settings, path, include_version=True):\n        \"\"\"Constructs a versioned url for the given path.\n\n        This method may be overridden in subclasses (but note that it\n        is a class method rather than an instance method).  Subclasses\n        are only required to implement the signature\n        ``make_static_url(cls, settings, path)``; other keyword\n        arguments may be passed through `~RequestHandler.static_url`\n        but are not standard.\n\n        ``settings`` is the `Application.settings` dictionary.  ``path``\n        is the static path being requested.  The url returned should be\n        relative to the current host.\n\n        ``include_version`` determines whether the generated URL should\n        include the query string containing the version hash of the\n        file corresponding to the given ``path``.\n\n        \"\"\"\n        url = settings.get('static_url_prefix', '/static/') + path\n        if not include_version:\n            return url\n\n        version_hash = cls.get_version(settings, path)\n        if not version_hash:\n            return url\n\n        return '%s?v=%s' % (url, version_hash)\n\n    def parse_url_path(self, url_path):\n        \"\"\"Converts a static URL path into a filesystem path.\n\n        ``url_path`` is the path component of the URL with\n        ``static_url_prefix`` removed.  The return value should be\n        filesystem path relative to ``static_path``.\n\n        This is the inverse of `make_static_url`.\n        \"\"\"\n        if os.path.sep != \"/\":\n            url_path = url_path.replace(\"/\", os.path.sep)\n        return url_path\n\n    @classmethod\n    def get_version(cls, settings, path):\n        \"\"\"Generate the version string to be used in static URLs.\n\n        ``settings`` is the `Application.settings` dictionary and ``path``\n        is the relative location of the requested asset on the filesystem.\n        The returned value should be a string, or ``None`` if no version\n        could be determined.\n\n        .. versionchanged:: 3.1\n           This method was previously recommended for subclasses to override;\n           `get_content_version` is now preferred as it allows the base\n           class to handle caching of the result.\n        \"\"\"\n        abs_path = cls.get_absolute_path(settings['static_path'], path)\n        return cls._get_cached_version(abs_path)\n\n    @classmethod\n    def _get_cached_version(cls, abs_path):\n        with cls._lock:\n            hashes = cls._static_hashes\n            if abs_path not in hashes:\n                try:\n                    hashes[abs_path] = cls.get_content_version(abs_path)\n                except Exception:\n                    gen_log.error(\"Could not open static file %r\", abs_path)\n                    hashes[abs_path] = None\n            hsh = hashes.get(abs_path)\n            if hsh:\n                return hsh\n        return None\n\n\nclass FallbackHandler(RequestHandler):\n    \"\"\"A `RequestHandler` that wraps another HTTP server callback.\n\n    The fallback is a callable object that accepts an\n    `~.httputil.HTTPServerRequest`, 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    Applications are not expected to create their own OutputTransforms\n    or interact with them directly; the framework chooses which transforms\n    (if any) to apply.\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    .. versionchanged:: 4.0\n        Now compresses all mime types beginning with ``text/``, instead\n        of just a whitelist. (the whitelist is still used for certain\n        non-text mime types).\n    \"\"\"\n    # Whitelist of compressible mime types (in addition to any types\n    # beginning with \"text/\").\n    CONTENT_TYPES = set([\"application/javascript\", \"application/x-javascript\",\n                         \"application/xml\", \"application/atom+xml\",\n                         \"application/json\", \"application/xhtml+xml\"])\n    # Python's GzipFile defaults to level 9, while most other gzip\n    # tools (including gzip itself) default to 6, which is probably a\n    # better CPU/size tradeoff.\n    GZIP_LEVEL = 6\n    # Responses that are too short are unlikely to benefit from gzipping\n    # after considering the \"Content-Encoding: gzip\" header and the header\n    # inside the gzip encoding.\n    # Note that responses written in multiple chunks will be compressed\n    # regardless of size.\n    MIN_LENGTH = 1024\n\n    def __init__(self, request):\n        self._gzipping = \"gzip\" in request.headers.get(\"Accept-Encoding\", \"\")\n\n    def _compressible_type(self, ctype):\n        return ctype.startswith('text/') or ctype in self.CONTENT_TYPES\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 = self._compressible_type(ctype) and \\\n                (not finishing or len(chunk) >= self.MIN_LENGTH) 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                                            compresslevel=self.GZIP_LEVEL)\n            chunk = self.transform_chunk(chunk, finishing)\n            if \"Content-Length\" in headers:\n                # The original content length is no longer correct.\n                # If this is the last (and only) chunk, we can set the new\n                # content-length; otherwise we remove it and fall back to\n                # chunked encoding.\n                if finishing:\n                    headers[\"Content-Length\"] = str(len(chunk))\n                else:\n                    del headers[\"Content-Length\"]\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\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    If you configure a login url with a query parameter, Tornado will\n    assume you know what you're doing and use it as-is.  If not, it\n    will add a `next` parameter so the login page knows where to send\n    you once you're logged in.\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    Subclasses of UIModule must override the `render` method.\n    \"\"\"\n    def __init__(self, handler):\n        self.handler = handler\n        self.request = handler.request\n        self.ui = handler.ui\n        self.locale = handler.locale\n\n    @property\n    def current_user(self):\n        return self.handler.current_user\n\n    def render(self, *args, **kwargs):\n        \"\"\"Override in subclasses to return this module's output.\"\"\"\n        raise NotImplementedError()\n\n    def embedded_javascript(self):\n        \"\"\"Override to return a JavaScript string\n        to be embedded in the page.\"\"\"\n        return None\n\n    def javascript_files(self):\n        \"\"\"Override to return a list of JavaScript files needed by this module.\n\n        If the return values are relative paths, they will be passed to\n        `RequestHandler.static_url`; otherwise they will be used as-is.\n        \"\"\"\n        return None\n\n    def embedded_css(self):\n        \"\"\"Override to return a CSS string\n        that will be embedded in the page.\"\"\"\n        return None\n\n    def css_files(self):\n        \"\"\"Override to returns a list of CSS files required by this module.\n\n        If the return values are relative paths, they will be passed to\n        `RequestHandler.static_url`; otherwise they will be used as-is.\n        \"\"\"\n        return None\n\n    def html_head(self):\n        \"\"\"Override to return an HTML string that will be put in the <head/>\n        element.\n        \"\"\"\n        return None\n\n    def html_body(self):\n        \"\"\"Override to return an HTML string that will be put at the end of\n        the <body/> element.\n        \"\"\"\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)):\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)):\n                result.append(f)\n            else:\n                result.extend(f)\n        return result\n\n    def html_head(self):\n        return \"\".join(self._get_resources(\"html_head\"))\n\n    def html_body(self):\n        return \"\".join(self._get_resources(\"html_body\"))\n\n\nclass _UIModuleNamespace(object):\n    \"\"\"Lazy namespace which creates UIModule proxies bound to a handler.\"\"\"\n    def __init__(self, handler, ui_modules):\n        self.handler = handler\n        self.ui_modules = ui_modules\n\n    def __getitem__(self, key):\n        return self.handler._ui_module(key, self.ui_modules[key])\n\n    def __getattr__(self, key):\n        try:\n            return self[key]\n        except KeyError as e:\n            raise AttributeError(str(e))\n\n\nclass URLSpec(object):\n    \"\"\"Specifies mappings between URLs and handlers.\"\"\"\n    def __init__(self, pattern, handler, 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``: `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\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        self.handler_class = handler\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                try:\n                    unescaped_fragment = re_unescape(fragment)\n                except ValueError as exc:\n                    raise ValueError(exc.args[0] + '; invalid url: %r' % pattern)\n                pieces.append(re_unescape(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)):\n                a = str(a)\n            converted_args.append(escape.url_escape(utf8(a), plus=False))\n        return self._path % tuple(converted_args)\n\nurl = URLSpec\n\n\nif hasattr(hmac, 'compare_digest'):  # python 3.3\n    _time_independent_equals = hmac.compare_digest\nelse:\n    def _time_independent_equals(a, b):\n        if len(a) != len(b):\n            return False\n        result = 0\n        if isinstance(a[0], int):  # python3 byte strings\n            for x, y in zip(a, b):\n                result |= x ^ y\n        else:  # python2\n            for x, y in zip(a, b):\n                result |= ord(x) ^ ord(y)\n        return result == 0\n\n\ndef create_signed_value(secret, name, value, version=None, clock=None,\n                        key_version=None):\n    if version is None:\n        version = DEFAULT_SIGNED_VALUE_VERSION\n    if clock is None:\n        clock = time.time\n\n    timestamp = utf8(str(int(clock())))\n    value = base64.b64encode(utf8(value))\n    if version == 1:\n        signature = _create_signature_v1(secret, name, value, timestamp)\n        value = b\"|\".join([value, timestamp, signature])\n        return value\n    elif version == 2:\n        # The v2 format consists of a version number and a series of\n        # length-prefixed fields \"%d:%s\", the last of which is a\n        # signature, all separated by pipes.  All numbers are in\n        # decimal format with no leading zeros.  The signature is an\n        # HMAC-SHA256 of the whole string up to that point, including\n        # the final pipe.\n        #\n        # The fields are:\n        # - format version (i.e. 2; no length prefix)\n        # - key version (integer, default is 0)\n        # - timestamp (integer seconds since epoch)\n        # - name (not encoded; assumed to be ~alphanumeric)\n        # - value (base64-encoded)\n        # - signature (hex-encoded; no length prefix)\n        def format_field(s):\n            return utf8(\"%d:\" % len(s)) + utf8(s)\n        to_sign = b\"|\".join([\n            b\"2\",\n            format_field(str(key_version or 0)),\n            format_field(timestamp),\n            format_field(name),\n            format_field(value),\n            b''])\n\n        if isinstance(secret, dict):\n            assert key_version is not None, 'Key version must be set when sign key dict is used'\n            assert version >= 2, 'Version must be at least 2 for key version support'\n            secret = secret[key_version]\n\n        signature = _create_signature_v2(secret, to_sign)\n        return to_sign + signature\n    else:\n        raise ValueError(\"Unsupported version %d\" % version)\n\n# A leading version number in decimal\n# with no leading zeros, followed by a pipe.\n_signed_value_version_re = re.compile(br\"^([1-9][0-9]*)\\|(.*)$\")\n\n\ndef _get_version(value):\n    # Figures out what version value is.  Version 1 did not include an\n    # explicit version field and started with arbitrary base64 data,\n    # which makes this tricky.\n    m = _signed_value_version_re.match(value)\n    if m is None:\n        version = 1\n    else:\n        try:\n            version = int(m.group(1))\n            if version > 999:\n                # Certain payloads from the version-less v1 format may\n                # be parsed as valid integers.  Due to base64 padding\n                # restrictions, this can only happen for numbers whose\n                # length is a multiple of 4, so we can treat all\n                # numbers up to 999 as versions, and for the rest we\n                # fall back to v1 format.\n                version = 1\n        except ValueError:\n            version = 1\n    return version\n\n\ndef decode_signed_value(secret, name, value, max_age_days=31,\n                        clock=None, min_version=None):\n    if clock is None:\n        clock = time.time\n    if min_version is None:\n        min_version = DEFAULT_SIGNED_VALUE_MIN_VERSION\n    if min_version > 2:\n        raise ValueError(\"Unsupported min_version %d\" % min_version)\n    if not value:\n        return None\n\n    value = utf8(value)\n    version = _get_version(value)\n\n    if version < min_version:\n        return None\n    if version == 1:\n        return _decode_signed_value_v1(secret, name, value,\n                                       max_age_days, clock)\n    elif version == 2:\n        return _decode_signed_value_v2(secret, name, value,\n                                       max_age_days, clock)\n    else:\n        return None\n\n\ndef _decode_signed_value_v1(secret, name, value, max_age_days, clock):\n    parts = utf8(value).split(b\"|\")\n    if len(parts) != 3:\n        return None\n    signature = _create_signature_v1(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 < clock() - max_age_days * 86400:\n        gen_log.warning(\"Expired cookie %r\", value)\n        return None\n    if timestamp > clock() + 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\",\n                        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 _decode_fields_v2(value):\n    def _consume_field(s):\n        length, _, rest = s.partition(b':')\n        n = int(length)\n        field_value = rest[:n]\n        # In python 3, indexing bytes returns small integers; we must\n        # use a slice to get a byte string as in python 2.\n        if rest[n:n + 1] != b'|':\n            raise ValueError(\"malformed v2 signed value field\")\n        rest = rest[n + 1:]\n        return field_value, rest\n\n    rest = value[2:]  # remove version number\n    key_version, rest = _consume_field(rest)\n    timestamp, rest = _consume_field(rest)\n    name_field, rest = _consume_field(rest)\n    value_field, passed_sig = _consume_field(rest)\n    return int(key_version), timestamp, name_field, value_field, passed_sig\n\n\ndef _decode_signed_value_v2(secret, name, value, max_age_days, clock):\n    try:\n        key_version, timestamp, name_field, value_field, passed_sig = _decode_fields_v2(value)\n    except ValueError:\n        return None\n    signed_string = value[:-len(passed_sig)]\n\n    if isinstance(secret, dict):\n        try:\n            secret = secret[key_version]\n        except KeyError:\n            return None\n\n    expected_sig = _create_signature_v2(secret, signed_string)\n    if not _time_independent_equals(passed_sig, expected_sig):\n        return None\n    if name_field != utf8(name):\n        return None\n    timestamp = int(timestamp)\n    if timestamp < clock() - max_age_days * 86400:\n        # The signature has expired.\n        return None\n    try:\n        return base64.b64decode(value_field)\n    except Exception:\n        return None\n\n\ndef get_signature_key_version(value):\n    value = utf8(value)\n    version = _get_version(value)\n    if version < 2:\n        return None\n    try:\n        key_version, _, _, _, _ = _decode_fields_v2(value)\n    except ValueError:\n        return None\n\n    return key_version\n\n\ndef _create_signature_v1(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\n\ndef _create_signature_v2(secret, s):\n    hash = hmac.new(utf8(secret), digestmod=hashlib.sha256)\n    hash.update(utf8(s))\n    return utf8(hash.hexdigest())\n\n\ndef _unquote_or_none(s):\n    \"\"\"None-safe wrapper around url_unescape to handle unamteched optional\n    groups correctly.\n\n    Note that args are passed as bytes so the handler can decide what\n    encoding to use.\n    \"\"\"\n    if s is None:\n        return s\n    return escape.url_unescape(s, encoding=None, plus=False)\n",
            "header": {
                "file": {
                    "path": "tornado/web.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "a5301db1",
                "new_commit_hash": "b45363cc",
                "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": 3024,
                            "length": 6
                        },
                        "new_range": {
                            "start": 3024,
                            "length": 10
                        },
                        "section": "class URLSpec(object):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "                if paren_loc >= 0:",
                                "type": "context"
                            },
                            {
                                "content": "                    pieces.append('%s' + fragment[paren_loc + 1:])",
                                "type": "context"
                            },
                            {
                                "content": "            else:",
                                "type": "context"
                            },
                            {
                                "content": "                try:",
                                "type": "added"
                            },
                            {
                                "content": "                    unescaped_fragment = re_unescape(fragment)",
                                "type": "added"
                            },
                            {
                                "content": "                except ValueError as exc:",
                                "type": "added"
                            },
                            {
                                "content": "                    raise ValueError(exc.args[0] + '; invalid url: %r' % pattern)",
                                "type": "added"
                            },
                            {
                                "content": "                pieces.append(re_unescape(fragment))",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        return (''.join(pieces), self.regex.groups)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/web.py",
                            "type": "method",
                            "name": "URLSpec._find_groups",
                            "content": "class URLSpec(object):\n    \"\"\"Specifies mappings between URLs and handlers.\"\"\"\n    def __init__(self, pattern, handler, 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``: `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\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        self.handler_class = handler\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                try:\n                    unescaped_fragment = re_unescape(fragment)\n                except ValueError as exc:\n                    raise ValueError(exc.args[0] + '; invalid url: %r' % pattern)\n                pieces.append(re_unescape(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)):\n                a = str(a)\n            converted_args.append(escape.url_escape(utf8(a), plus=False))\n        return self._path % tuple(converted_args)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 3003,
                            "end_lineno": 3033,
                            "parent": {
                                "file_name": "tornado/web.py",
                                "type": "class",
                                "name": "URLSpec",
                                "content": "class URLSpec(object):\n    \"\"\"Specifies mappings between URLs and handlers.\"\"\"\n    def __init__(self, pattern, handler, 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``: `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\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        self.handler_class = handler\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                try:\n                    unescaped_fragment = re_unescape(fragment)\n                except ValueError as exc:\n                    raise ValueError(exc.args[0] + '; invalid url: %r' % pattern)\n                pieces.append(re_unescape(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)):\n                a = str(a)\n            converted_args.append(escape.url_escape(utf8(a), plus=False))\n        return self._path % tuple(converted_args)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 2964,
                                "end_lineno": 3047,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/web.py",
                            "type": "class",
                            "name": "URLSpec",
                            "content": "class URLSpec(object):\n    \"\"\"Specifies mappings between URLs and handlers.\"\"\"\n    def __init__(self, pattern, handler, 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``: `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\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        self.handler_class = handler\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                try:\n                    unescaped_fragment = re_unescape(fragment)\n                except ValueError as exc:\n                    raise ValueError(exc.args[0] + '; invalid url: %r' % pattern)\n                pieces.append(re_unescape(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)):\n                a = str(a)\n            converted_args.append(escape.url_escape(utf8(a), plus=False))\n        return self._path % tuple(converted_args)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 2964,
                            "end_lineno": 3047,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "e85e0b68ab28ccd8728a87e5791dc30732192ef3^",
    "new_commit_hash": "e85e0b68ab28ccd8728a87e5791dc30732192ef3",
    "commit_message": "re_unescape with a much simpler method; raise TypeError on invalid input",
    "commit_date": "2016-01-06T00:43:20+08:00",
    "metadata": {}
}
{
    "repo_name": "tornado",
    "new_commit_hash": "e85e0b68ab28ccd8728a87e5791dc30732192ef3",
    "test_file_codes": [
        "# coding: utf-8\nfrom __future__ import absolute_import, division, print_function, with_statement\nimport re\nimport sys\nimport datetime\n\nimport tornado.escape\nfrom tornado.escape import utf8\nfrom tornado.util import raise_exc_info, Configurable, exec_in, ArgReplacer, timedelta_to_seconds, import_object, re_unescape\nfrom tornado.test.util import unittest\n\ntry:\n    from cStringIO import StringIO  # py2\nexcept ImportError:\n    from io import StringIO  # py3\n\n\nclass RaiseExcInfoTest(unittest.TestCase):\n    def test_two_arg_exception(self):\n        # This test would fail on python 3 if raise_exc_info were simply\n        # a three-argument raise statement, because TwoArgException\n        # doesn't have a \"copy constructor\"\n        class TwoArgException(Exception):\n            def __init__(self, a, b):\n                super(TwoArgException, self).__init__()\n                self.a, self.b = a, b\n\n        try:\n            raise TwoArgException(1, 2)\n        except TwoArgException:\n            exc_info = sys.exc_info()\n        try:\n            raise_exc_info(exc_info)\n            self.fail(\"didn't get expected exception\")\n        except TwoArgException as e:\n            self.assertIs(e, exc_info[1])\n\n\nclass TestConfigurable(Configurable):\n    @classmethod\n    def configurable_base(cls):\n        return TestConfigurable\n\n    @classmethod\n    def configurable_default(cls):\n        return TestConfig1\n\n\nclass TestConfig1(TestConfigurable):\n    def initialize(self, pos_arg=None, a=None):\n        self.a = a\n        self.pos_arg = pos_arg\n\n\nclass TestConfig2(TestConfigurable):\n    def initialize(self, pos_arg=None, b=None):\n        self.b = b\n        self.pos_arg = pos_arg\n\n\nclass ConfigurableTest(unittest.TestCase):\n    def setUp(self):\n        self.saved = TestConfigurable._save_configuration()\n\n    def tearDown(self):\n        TestConfigurable._restore_configuration(self.saved)\n\n    def checkSubclasses(self):\n        # no matter how the class is configured, it should always be\n        # possible to instantiate the subclasses directly\n        self.assertIsInstance(TestConfig1(), TestConfig1)\n        self.assertIsInstance(TestConfig2(), TestConfig2)\n\n        obj = TestConfig1(a=1)\n        self.assertEqual(obj.a, 1)\n        obj = TestConfig2(b=2)\n        self.assertEqual(obj.b, 2)\n\n    def test_default(self):\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertIs(obj.a, None)\n\n        obj = TestConfigurable(a=1)\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 1)\n\n        self.checkSubclasses()\n\n    def test_config_class(self):\n        TestConfigurable.configure(TestConfig2)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertIs(obj.b, None)\n\n        obj = TestConfigurable(b=2)\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 2)\n\n        self.checkSubclasses()\n\n    def test_config_args(self):\n        TestConfigurable.configure(None, a=3)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 3)\n\n        obj = TestConfigurable(42, a=4)\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 4)\n        self.assertEqual(obj.pos_arg, 42)\n\n        self.checkSubclasses()\n        # args bound in configure don't apply when using the subclass directly\n        obj = TestConfig1()\n        self.assertIs(obj.a, None)\n\n    def test_config_class_args(self):\n        TestConfigurable.configure(TestConfig2, b=5)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 5)\n\n        obj = TestConfigurable(42, b=6)\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 6)\n        self.assertEqual(obj.pos_arg, 42)\n\n        self.checkSubclasses()\n        # args bound in configure don't apply when using the subclass directly\n        obj = TestConfig2()\n        self.assertIs(obj.b, None)\n\n\nclass UnicodeLiteralTest(unittest.TestCase):\n    def test_unicode_escapes(self):\n        self.assertEqual(utf8(u'\\u00e9'), b'\\xc3\\xa9')\n\n\nclass ExecInTest(unittest.TestCase):\n    # This test is python 2 only because there are no new future imports\n    # defined in python 3 yet.\n    @unittest.skipIf(sys.version_info >= print_function.getMandatoryRelease(),\n                     'no testable future imports')\n    def test_no_inherit_future(self):\n        # This file has from __future__ import print_function...\n        f = StringIO()\n        print('hello', file=f)\n        # ...but the template doesn't\n        exec_in('print >> f, \"world\"', dict(f=f))\n        self.assertEqual(f.getvalue(), 'hello\\nworld\\n')\n\n\nclass ArgReplacerTest(unittest.TestCase):\n    def setUp(self):\n        def function(x, y, callback=None, z=None):\n            pass\n        self.replacer = ArgReplacer(function, 'callback')\n\n    def test_omitted(self):\n        args = (1, 2)\n        kwargs = dict()\n        self.assertIs(self.replacer.get_old_value(args, kwargs), None)\n        self.assertEqual(self.replacer.replace('new', args, kwargs),\n                         (None, (1, 2), dict(callback='new')))\n\n    def test_position(self):\n        args = (1, 2, 'old', 3)\n        kwargs = dict()\n        self.assertEqual(self.replacer.get_old_value(args, kwargs), 'old')\n        self.assertEqual(self.replacer.replace('new', args, kwargs),\n                         ('old', [1, 2, 'new', 3], dict()))\n\n    def test_keyword(self):\n        args = (1,)\n        kwargs = dict(y=2, callback='old', z=3)\n        self.assertEqual(self.replacer.get_old_value(args, kwargs), 'old')\n        self.assertEqual(self.replacer.replace('new', args, kwargs),\n                         ('old', (1,), dict(y=2, callback='new', z=3)))\n\n\nclass TimedeltaToSecondsTest(unittest.TestCase):\n    def test_timedelta_to_seconds(self):\n        time_delta = datetime.timedelta(hours=1)\n        self.assertEqual(timedelta_to_seconds(time_delta), 3600.0)\n\n\nclass ImportObjectTest(unittest.TestCase):\n    def test_import_member(self):\n        self.assertIs(import_object('tornado.escape.utf8'), utf8)\n\n    def test_import_member_unicode(self):\n        self.assertIs(import_object(u'tornado.escape.utf8'), utf8)\n\n    def test_import_module(self):\n        self.assertIs(import_object('tornado.escape'), tornado.escape)\n\n    def test_import_module_unicode(self):\n        # The internal implementation of __import__ differs depending on\n        # whether the thing being imported is a module or not.\n        # This variant requires a byte string in python 2.\n        self.assertIs(import_object(u'tornado.escape'), tornado.escape)\n\n\nclass ReUnescapeTest(unittest.TestCase):\n    def test_re_unescape(self):\n        test_strings = (\n            '/favicon.ico',\n            'index.html',\n            'Hello, World!',\n            '!$@#%;',\n        )\n        for string in test_strings:\n            self.assertEqual(string, re_unescape(re.escape(string)))\n\n    def test_re_unescape_raises_error_on_invalid_input(self):\n        with self.assertRaises(ValueError):\n            re_unescape('\\\\d')\n        with self.assertRaises(ValueError):\n            re_unescape('\\\\b')\n        with self.assertRaises(ValueError):\n            re_unescape('\\\\Z')\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 600ms\nPrepared 1 package in 1.00s\nInstalled 1 package in 0.73ms\n + tornado==4.4.dev1 (from file:///home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e85e0b68ab28ccd8728a87e5791dc30732192ef3)\nResolved 29 packages in 12ms\nInstalled 29 packages in 27ms\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_e85e0b68ab28ccd8728a87e5791dc30732192ef3\n.................\ncollected 17 items\n\n==================== short test summary info ====================\nPASSED r2e_tests.test_1::ArgReplacerTest::test_keyword\nPASSED r2e_tests.test_1::ArgReplacerTest::test_omitted\nPASSED r2e_tests.test_1::ArgReplacerTest::test_position\nPASSED r2e_tests.test_1::ConfigurableTest::test_config_args\nPASSED r2e_tests.test_1::ConfigurableTest::test_config_class\nPASSED r2e_tests.test_1::ConfigurableTest::test_config_class_args\nPASSED r2e_tests.test_1::ConfigurableTest::test_default\nSKIPPED r2e_tests.test_1::ExecInTest::test_no_inherit_future\nPASSED r2e_tests.test_1::ImportObjectTest::test_import_member\nPASSED r2e_tests.test_1::ImportObjectTest::test_import_member_unicode\nPASSED r2e_tests.test_1::ImportObjectTest::test_import_module\nPASSED r2e_tests.test_1::ImportObjectTest::test_import_module_unicode\nPASSED r2e_tests.test_1::RaiseExcInfoTest::test_two_arg_exception\nPASSED r2e_tests.test_1::ReUnescapeTest::test_re_unescape\nPASSED r2e_tests.test_1::ReUnescapeTest::test_re_unescape_raises_error_on_invalid_input\nPASSED r2e_tests.test_1::TimedeltaToSecondsTest::test_timedelta_to_seconds\nPASSED r2e_tests.test_1::UnicodeLiteralTest::test_unicode_escapes\n=================== 16 passed, 1 skipped in 0.00s ===================\n",
    "new_commit_res_stderr": "",
    "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_e85e0b68ab28ccd8728a87e5791dc30732192ef3\n.................\ncollected 17 items\n\n=================================== FAILURES ===================================\n__________ ReUnescapeTest.test_re_unescape_raises_error_on_invalid_input __________\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_e85e0b68ab28ccd8728a87e5791dc30732192ef3/r2e_tests/test_1.py\", line 218, in test_re_unescape_raises_error_on_invalid_input\n    re_unescape('\\\\d')\nAssertionError: ValueError not raised\n\n==================== short test summary info ====================\nPASSED r2e_tests.test_1::ArgReplacerTest::test_keyword\nPASSED r2e_tests.test_1::ArgReplacerTest::test_omitted\nPASSED r2e_tests.test_1::ArgReplacerTest::test_position\nPASSED r2e_tests.test_1::ConfigurableTest::test_config_args\nPASSED r2e_tests.test_1::ConfigurableTest::test_config_class\nPASSED r2e_tests.test_1::ConfigurableTest::test_config_class_args\nPASSED r2e_tests.test_1::ConfigurableTest::test_default\nSKIPPED r2e_tests.test_1::ExecInTest::test_no_inherit_future\nPASSED r2e_tests.test_1::ImportObjectTest::test_import_member\nPASSED r2e_tests.test_1::ImportObjectTest::test_import_member_unicode\nPASSED r2e_tests.test_1::ImportObjectTest::test_import_module\nPASSED r2e_tests.test_1::ImportObjectTest::test_import_module_unicode\nPASSED r2e_tests.test_1::RaiseExcInfoTest::test_two_arg_exception\nPASSED r2e_tests.test_1::ReUnescapeTest::test_re_unescape\nFAILED r2e_tests.test_1::ReUnescapeTest::test_re_unescape_raises_error_on_invalid_input\nPASSED r2e_tests.test_1::TimedeltaToSecondsTest::test_timedelta_to_seconds\nPASSED r2e_tests.test_1::UnicodeLiteralTest::test_unicode_escapes\n=================== 1 failed, 15 passed, 1 skipped in 0.00s ===================\n",
    "old_commit_res_stderr": ""
}
tornado/test/util_test.py tornado/util.py tornado/web.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** `re_unescape` Does Not Raise `ValueError` for Invalid Escape Sequences

**Description:**
The `re_unescape` function is expected to raise a `ValueError` when it encounters invalid escape sequences. However, when provided with inputs like `'\\d'`, `'\\b'`, or `'\\Z'`, the function does not raise the necessary exceptions. This allows invalid escape sequences to be processed incorrectly, which can lead to unexpected behavior in the application.

**Example Buggy Code:**
```python
def test_re_unescape_invalid_sequences():
    re_unescape('\\d')  # Expected to raise ValueError
    re_unescape('\\b')  # Expected to raise ValueError
    re_unescape('\\Z')  # Expected to raise ValueError
```

**Expected Behavior:**
When `re_unescape` receives an invalid escape sequence such as `'\\d'`, `'\\b'`, or `'\\Z'`, it should raise a `ValueError` to indicate that the input is invalid and cannot be unescaped properly.

**Actual Behavior:**
The `re_unescape` function does not raise any errors when provided with invalid escape sequences. Instead, it processes the input without signaling any issues, allowing potentially malformed data to pass through unchecked.

[/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/util.py
"""Miscellaneous utility functions and classes.

This module is used internally by Tornado.  It is not necessarily expected
that the functions and classes defined here will be useful to other
applications, but they are documented here in case they are.

The one public-facing part of this module is the `Configurable` class
and its `~Configurable.configure` method, which becomes a part of the
interface of its subclasses, including `.AsyncHTTPClient`, `.IOLoop`,
and `.Resolver`.
"""

from __future__ import absolute_import, division, print_function, with_statement

import array
import os
import re
import sys
import zlib


try:
    xrange  # py2
except NameError:
    xrange = range  # py3

# inspect.getargspec() raises DeprecationWarnings in Python 3.5.
# The two functions have compatible interfaces for the parts we need.
try:
    from inspect import getfullargspec as getargspec  # py3
except ImportError:
    from inspect import getargspec  # py2


class ObjectDict(dict):
    """Makes a dictionary behave like an object, with attribute-style access.
    """
    def __getattr__(self, name):
        try:
            return self[name]
        except KeyError:
            raise AttributeError(name)

    def __setattr__(self, name, value):
        self[name] = value


class GzipDecompressor(object):
    """Streaming gzip decompressor.

    The interface is like that of `zlib.decompressobj` (without some of the
    optional arguments, but it understands gzip headers and checksums.
    """
    def __init__(self):
        # Magic parameter makes zlib module understand gzip header
        # http://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib
        # This works on cpython and pypy, but not jython.
        self.decompressobj = zlib.decompressobj(16 + zlib.MAX_WBITS)

    def decompress(self, value, max_length=None):
        """Decompress a chunk, returning newly-available data.

        Some data may be buffered for later processing; `flush` must
        be called when there is no more input data to ensure that
        all data was processed.

        If ``max_length`` is given, some input data may be left over
        in ``unconsumed_tail``; you must retrieve this value and pass
        it back to a future call to `decompress` if it is not empty.
        """
        return self.decompressobj.decompress(value, max_length)

    @property
    def unconsumed_tail(self):
        """Returns the unconsumed portion left over
        """
        return self.decompressobj.unconsumed_tail

    def flush(self):
        """Return any remaining buffered data not yet returned by decompress.

        Also checks for errors such as truncated input.
        No other methods may be called on this object after `flush`.
        """
        return self.decompressobj.flush()


if not isinstance(b'', type('')):
    unicode_type = str
    basestring_type = str
else:
    # These names don't exist in py3, so use noqa comments to disable
    # warnings in flake8.
    unicode_type = unicode  # noqa
    basestring_type = basestring  # noqa


def import_object(name):
    """Imports an object by name.

    import_object('x') is equivalent to 'import x'.
    import_object('x.y.z') is equivalent to 'from x.y import z'.

    >>> import tornado.escape
    >>> import_object('tornado.escape') is tornado.escape
    True
    >>> import_object('tornado.escape.utf8') is tornado.escape.utf8
    True
    >>> import_object('tornado') is tornado
    True
    >>> import_object('tornado.missing_module')
    Traceback (most recent call last):
        ...
    ImportError: No module named missing_module
    """
    if isinstance(name, unicode_type) and str is not unicode_type:
        # On python 2 a byte string is required.
        name = name.encode('utf-8')
    if name.count('.') == 0:
        return __import__(name, None, None)

    parts = name.split('.')
    obj = __import__('.'.join(parts[:-1]), None, None, [parts[-1]], 0)
    try:
        return getattr(obj, parts[-1])
    except AttributeError:
        raise ImportError("No module named %s" % parts[-1])


# Deprecated alias that was used before we dropped py25 support.
# Left here in case anyone outside Tornado is using it.
bytes_type = bytes

if sys.version_info > (3,):
    exec("""
def raise_exc_info(exc_info):
    raise exc_info[1].with_traceback(exc_info[2])

def exec_in(code, glob, loc=None):
    if isinstance(code, str):
        code = compile(code, '<string>', 'exec', dont_inherit=True)
    exec(code, glob, loc)
""")
else:
    exec("""
def raise_exc_info(exc_info):
    raise exc_info[0], exc_info[1], exc_info[2]

def exec_in(code, glob, loc=None):
    if isinstance(code, basestring):
        # exec(string) inherits the caller's future imports; compile
        # the string first to prevent that.
        code = compile(code, '<string>', 'exec', dont_inherit=True)
    exec code in glob, loc
""")


def errno_from_exception(e):
    """Provides the errno from an Exception object.

    There are cases that the errno attribute was not set so we pull
    the errno out of the args but if someone instantiates an Exception
    without any args you will get a tuple error. So this function
    abstracts all that behavior to give you a safe way to get the
    errno.
    """

    if hasattr(e, 'errno'):
        return e.errno
    elif e.args:
        return e.args[0]
    else:
        return None


_re_unescape_split_pattern = re.compile(r'(\\[^0])')
# re.escape('\x00') is a special case

def re_unescape(s):
    '''
    unescape a string escaped by ``re.escape()``
    '''
    parts = []
    for i, splited in enumerate(_re_unescape_split_pattern.split(s)):
        if i % 2:
            parts.append(splited[1])
        else:
            parts.append(splited.replace(r'\000', '\000'))
    return ''.join(parts)


class Configurable(object):
    """Base class for configurable interfaces.

    A configurable interface is an (abstract) class whose constructor
    acts as a factory function for one of its implementation subclasses.
    The implementation subclass as well as optional keyword arguments to
    its initializer can be set globally at runtime with `configure`.

    By using the constructor as the factory method, the interface
    looks like a normal class, `isinstance` works as usual, etc.  This
    pattern is most useful when the choice of implementation is likely
    to be a global decision (e.g. when `~select.epoll` is available,
    always use it instead of `~select.select`), or when a
    previously-monolithic class has been split into specialized
    subclasses.

    Configurable subclasses must define the class methods
    `configurable_base` and `configurable_default`, and use the instance
    method `initialize` instead of ``__init__``.
    """
    __impl_class = None
    __impl_kwargs = None

    def __new__(cls, *args, **kwargs):
        base = cls.configurable_base()
        init_kwargs = {}
        if cls is base:
            impl = cls.configured_class()
            if base.__impl_kwargs:
                init_kwargs.update(base.__impl_kwargs)
        else:
            impl = cls
        init_kwargs.update(kwargs)
        instance = super(Configurable, cls).__new__(impl)
        # initialize vs __init__ chosen for compatibility with AsyncHTTPClient
        # singleton magic.  If we get rid of that we can switch to __init__
        # here too.
        instance.initialize(*args, **init_kwargs)
        return instance

    @classmethod
    def configurable_base(cls):
        """Returns the base class of a configurable hierarchy.

        This will normally return the class in which it is defined.
        (which is *not* necessarily the same as the cls classmethod parameter).
        """
        raise NotImplementedError()

    @classmethod
    def configurable_default(cls):
        """Returns the implementation class to be used if none is configured."""
        raise NotImplementedError()

    def initialize(self):
        """Initialize a `Configurable` subclass instance.

        Configurable classes should use `initialize` instead of ``__init__``.

        .. versionchanged:: 4.2
           Now accepts positional arguments in addition to keyword arguments.
        """

    @classmethod
    def configure(cls, impl, **kwargs):
        """Sets the class to use when the base class is instantiated.

        Keyword arguments will be saved and added to the arguments passed
        to the constructor.  This can be used to set global defaults for
        some parameters.
        """
        base = cls.configurable_base()
        if isinstance(impl, (unicode_type, bytes)):
            impl = import_object(impl)
        if impl is not None and not issubclass(impl, cls):
            raise ValueError("Invalid subclass of %s" % cls)
        base.__impl_class = impl
        base.__impl_kwargs = kwargs

    @classmethod
    def configured_class(cls):
        """Returns the currently configured class."""
        base = cls.configurable_base()
        if cls.__impl_class is None:
            base.__impl_class = cls.configurable_default()
        return base.__impl_class

    @classmethod
    def _save_configuration(cls):
        base = cls.configurable_base()
        return (base.__impl_class, base.__impl_kwargs)

    @classmethod
    def _restore_configuration(cls, saved):
        base = cls.configurable_base()
        base.__impl_class = saved[0]
        base.__impl_kwargs = saved[1]


class ArgReplacer(object):
    """Replaces one value in an ``args, kwargs`` pair.

    Inspects the function signature to find an argument by name
    whether it is passed by position or keyword.  For use in decorators
    and similar wrappers.
    """
    def __init__(self, func, name):
        self.name = name
        try:
            self.arg_pos = self._getargnames(func).index(name)
        except ValueError:
            # Not a positional parameter
            self.arg_pos = None

    def _getargnames(self, func):
        try:
            return getargspec(func).args
        except TypeError:
            if hasattr(func, 'func_code'):
                # Cython-generated code has all the attributes needed
                # by inspect.getargspec, but the inspect module only
                # works with ordinary functions. Inline the portion of
                # getargspec that we need here. Note that for static
                # functions the @cython.binding(True) decorator must
                # be used (for methods it works out of the box).
                code = func.func_code
                return code.co_varnames[:code.co_argcount]
            raise

    def get_old_value(self, args, kwargs, default=None):
        """Returns the old value of the named argument without replacing it.

        Returns ``default`` if the argument is not present.
        """
        if self.arg_pos is not None and len(args) > self.arg_pos:
            return args[self.arg_pos]
        else:
            return kwargs.get(self.name, default)

    def replace(self, new_value, args, kwargs):
        """Replace the named argument in ``args, kwargs`` with ``new_value``.

        Returns ``(old_value, args, kwargs)``.  The returned ``args`` and
        ``kwargs`` objects may not be the same as the input objects, or
        the input objects may be mutated.

        If the named argument was not found, ``new_value`` will be added
        to ``kwargs`` and None will be returned as ``old_value``.
        """
        if self.arg_pos is not None and len(args) > self.arg_pos:
            # The arg to replace is passed positionally
            old_value = args[self.arg_pos]
            args = list(args)  # *args is normally a tuple
            args[self.arg_pos] = new_value
        else:
            # The arg to replace is either omitted or passed by keyword.
            old_value = kwargs.get(self.name)
            kwargs[self.name] = new_value
        return old_value, args, kwargs


def timedelta_to_seconds(td):
    """Equivalent to td.total_seconds() (introduced in python 2.7)."""
    return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 ** 6) / float(10 ** 6)


def _websocket_mask_python(mask, data):
    """Websocket masking function.

    `mask` is a `bytes` object of length 4; `data` is a `bytes` object of any length.
    Returns a `bytes` object of the same length as `data` with the mask applied
    as specified in section 5.3 of RFC 6455.

    This pure-python implementation may be replaced by an optimized version when available.
    """
    mask = array.array("B", mask)
    unmasked = array.array("B", data)
    for i in xrange(len(data)):
        unmasked[i] = unmasked[i] ^ mask[i % 4]
    if hasattr(unmasked, 'tobytes'):
        # tostring was deprecated in py32.  It hasn't been removed,
        # but since we turn on deprecation warnings in our tests
        # we need to use the right one.
        return unmasked.tobytes()
    else:
        return unmasked.tostring()

if (os.environ.get('TORNADO_NO_EXTENSION') or
        os.environ.get('TORNADO_EXTENSION') == '0'):
    # These environment variables exist to make it easier to do performance
    # comparisons; they are not guaranteed to remain supported in the future.
    _websocket_mask = _websocket_mask_python
else:
    try:
        from tornado.speedups import websocket_mask as _websocket_mask
    except ImportError:
        if os.environ.get('TORNADO_EXTENSION') == '1':
            raise
        _websocket_mask = _websocket_mask_python


def doctests():
    import doctest
    return doctest.DocTestSuite()

```
--- 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:** `re_unescape` Does Not Raise `ValueError` for Invalid Escape Sequences

**Description:**
The `re_unescape` function is expected to raise a `ValueError` when it encounters invalid escape sequences. However, when provided with inputs like `'\\d'`, `'\\b'`, or `'\\Z'`, the function does not raise the necessary exceptions. This allows invalid escape sequences to be processed incorrectly, which can lead to unexpected behavior in the application.

**Example Buggy Code:**
```python
def test_re_unescape_invalid_sequences():
    re_unescape('\\d')  # Expected to raise ValueError
    re_unescape('\\b')  # Expected to raise ValueError
    re_unescape('\\Z')  # Expected to raise ValueError
```

**Expected Behavior:**
When `re_unescape` receives an invalid escape sequence such as `'\\d'`, `'\\b'`, or `'\\Z'`, it should raise a `ValueError` to indicate that the input is invalid and cannot be unescaped properly.

**Actual Behavior:**
The `re_unescape` function does not raise any errors when provided with invalid escape sequences. Instead, it processes the input without signaling any issues, allowing potentially malformed data to pass through unchecked.

[/ISSUE]
{
    "ArgReplacerTest.test_keyword": "PASSED",
    "ArgReplacerTest.test_omitted": "PASSED",
    "ArgReplacerTest.test_position": "PASSED",
    "ConfigurableTest.test_config_args": "PASSED",
    "ConfigurableTest.test_config_class": "PASSED",
    "ConfigurableTest.test_config_class_args": "PASSED",
    "ConfigurableTest.test_default": "PASSED",
    "ImportObjectTest.test_import_member": "PASSED",
    "ImportObjectTest.test_import_member_unicode": "PASSED",
    "ImportObjectTest.test_import_module": "PASSED",
    "ImportObjectTest.test_import_module_unicode": "PASSED",
    "RaiseExcInfoTest.test_two_arg_exception": "PASSED",
    "ReUnescapeTest.test_re_unescape": "PASSED",
    "ReUnescapeTest.test_re_unescape_raises_error_on_invalid_input": "PASSED",
    "TimedeltaToSecondsTest.test_timedelta_to_seconds": "PASSED",
    "UnicodeLiteralTest.test_unicode_escapes": "PASSED"
}
diff --git a/tornado/util.py b/tornado/util.py
index e74be97c..a0401c14 100644
--- a/tornado/util.py
+++ b/tornado/util.py
@@ -173,20 +173,22 @@ def errno_from_exception(e):
         return None
 
 
-_re_unescape_split_pattern = re.compile(r'(\\[^0])')
-# re.escape('\x00') is a special case
+_alphanum = frozenset(
+    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
+
+def _re_unescape_replacement(match):
+    group = match.group(1)
+    if group[0] in _alphanum:
+        raise ValueError("cannot unescape '\\\\%s'" % group[0])
+    return group
+
+_re_unescape_pattern = re.compile(r'\\(.)', re.DOTALL)
 
 def re_unescape(s):
     '''
     unescape a string escaped by ``re.escape()``
     '''
-    parts = []
-    for i, splited in enumerate(_re_unescape_split_pattern.split(s)):
-        if i % 2:
-            parts.append(splited[1])
-        else:
-            parts.append(splited.replace(r'\000', '\000'))
-    return ''.join(parts)
+    return _re_unescape_pattern.sub(_re_unescape_replacement, s)
 
 
 class Configurable(object):
diff --git a/tornado/web.py b/tornado/web.py
index a5301db1..b45363cc 100644
--- a/tornado/web.py
+++ b/tornado/web.py
@@ -3024,6 +3024,10 @@ class URLSpec(object):
                 if paren_loc >= 0:
                     pieces.append('%s' + fragment[paren_loc + 1:])
             else:
+                try:
+                    unescaped_fragment = re_unescape(fragment)
+                except ValueError as exc:
+                    raise ValueError(exc.args[0] + '; invalid url: %r' % pattern)
                 pieces.append(re_unescape(fragment))
 
         return (''.join(pieces), self.regex.groups)
 

{"tornado/util.py": "\"\"\"Miscellaneous utility functions and classes.\n\nThis module is used internally by Tornado.  It is not necessarily expected\nthat the functions and classes defined here will be useful to other\napplications, but they are documented here in case they are.\n\nThe one public-facing part of this module is the `Configurable` class\nand its `~Configurable.configure` method, which becomes a part of the\ninterface of its subclasses, including `.AsyncHTTPClient`, `.IOLoop`,\nand `.Resolver`.\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nimport array\nimport os\nimport re\nimport sys\nimport zlib\n\n\ntry:\n    xrange  # py2\nexcept NameError:\n    xrange = range  # py3\n\n# inspect.getargspec() raises DeprecationWarnings in Python 3.5.\n# The two functions have compatible interfaces for the parts we need.\ntry:\n    from inspect import getfullargspec as getargspec  # py3\nexcept ImportError:\n    from inspect import getargspec  # py2\n\n\nclass ObjectDict(dict):\n    \"\"\"Makes a dictionary behave like an object, with attribute-style access.\n    \"\"\"\n    def __getattr__(self, name):\n        try:\n            return self[name]\n        except KeyError:\n            raise AttributeError(name)\n\n    def __setattr__(self, name, value):\n        self[name] = value\n\n\nclass GzipDecompressor(object):\n    \"\"\"Streaming gzip decompressor.\n\n    The interface is like that of `zlib.decompressobj` (without some of the\n    optional arguments, but it understands gzip headers and checksums.\n    \"\"\"\n    def __init__(self):\n        # Magic parameter makes zlib module understand gzip header\n        # http://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib\n        # This works on cpython and pypy, but not jython.\n        self.decompressobj = zlib.decompressobj(16 + zlib.MAX_WBITS)\n\n    def decompress(self, value, max_length=None):\n        \"\"\"Decompress a chunk, returning newly-available data.\n\n        Some data may be buffered for later processing; `flush` must\n        be called when there is no more input data to ensure that\n        all data was processed.\n\n        If ``max_length`` is given, some input data may be left over\n        in ``unconsumed_tail``; you must retrieve this value and pass\n        it back to a future call to `decompress` if it is not empty.\n        \"\"\"\n        return self.decompressobj.decompress(value, max_length)\n\n    @property\n    def unconsumed_tail(self):\n        \"\"\"Returns the unconsumed portion left over\n        \"\"\"\n        return self.decompressobj.unconsumed_tail\n\n    def flush(self):\n        \"\"\"Return any remaining buffered data not yet returned by decompress.\n\n        Also checks for errors such as truncated input.\n        No other methods may be called on this object after `flush`.\n        \"\"\"\n        return self.decompressobj.flush()\n\n\nif not isinstance(b'', type('')):\n    unicode_type = str\n    basestring_type = str\nelse:\n    # These names don't exist in py3, so use noqa comments to disable\n    # warnings in flake8.\n    unicode_type = unicode  # noqa\n    basestring_type = basestring  # noqa\n\n\ndef import_object(name):\n    \"\"\"Imports an object by name.\n\n    import_object('x') is equivalent to 'import x'.\n    import_object('x.y.z') is equivalent to 'from x.y import z'.\n\n    >>> import tornado.escape\n    >>> import_object('tornado.escape') is tornado.escape\n    True\n    >>> import_object('tornado.escape.utf8') is tornado.escape.utf8\n    True\n    >>> import_object('tornado') is tornado\n    True\n    >>> import_object('tornado.missing_module')\n    Traceback (most recent call last):\n        ...\n    ImportError: No module named missing_module\n    \"\"\"\n    if isinstance(name, unicode_type) and str is not unicode_type:\n        # On python 2 a byte string is required.\n        name = name.encode('utf-8')\n    if name.count('.') == 0:\n        return __import__(name, None, None)\n\n    parts = name.split('.')\n    obj = __import__('.'.join(parts[:-1]), None, None, [parts[-1]], 0)\n    try:\n        return getattr(obj, parts[-1])\n    except AttributeError:\n        raise ImportError(\"No module named %s\" % parts[-1])\n\n\n# Deprecated alias that was used before we dropped py25 support.\n# Left here in case anyone outside Tornado is using it.\nbytes_type = bytes\n\nif sys.version_info > (3,):\n    exec(\"\"\"\ndef raise_exc_info(exc_info):\n    raise exc_info[1].with_traceback(exc_info[2])\n\ndef exec_in(code, glob, loc=None):\n    if isinstance(code, str):\n        code = compile(code, '<string>', 'exec', dont_inherit=True)\n    exec(code, glob, loc)\n\"\"\")\nelse:\n    exec(\"\"\"\ndef raise_exc_info(exc_info):\n    raise exc_info[0], exc_info[1], exc_info[2]\n\ndef exec_in(code, glob, loc=None):\n    if isinstance(code, basestring):\n        # exec(string) inherits the caller's future imports; compile\n        # the string first to prevent that.\n        code = compile(code, '<string>', 'exec', dont_inherit=True)\n    exec code in glob, loc\n\"\"\")\n\n\ndef errno_from_exception(e):\n    \"\"\"Provides the errno from an Exception object.\n\n    There are cases that the errno attribute was not set so we pull\n    the errno out of the args but if someone instantiates an Exception\n    without any args you will get a tuple error. So this function\n    abstracts all that behavior to give you a safe way to get the\n    errno.\n    \"\"\"\n\n    if hasattr(e, 'errno'):\n        return e.errno\n    elif e.args:\n        return e.args[0]\n    else:\n        return None\n\n\n_re_unescape_split_pattern = re.compile(r'(\\\\[^0])')\n# re.escape('\\x00') is a special case\n\ndef re_unescape(s):\n    '''\n    unescape a string escaped by ``re.escape()``\n    '''\n    parts = []\n    for i, splited in enumerate(_re_unescape_split_pattern.split(s)):\n        if i % 2:\n            parts.append(splited[1])\n        else:\n            parts.append(splited.replace(r'\\000', '\\000'))\n    return ''.join(parts)\n\n\nclass Configurable(object):\n    \"\"\"Base class for configurable interfaces.\n\n    A configurable interface is an (abstract) class whose constructor\n    acts as a factory function for one of its implementation subclasses.\n    The implementation subclass as well as optional keyword arguments to\n    its initializer can be set globally at runtime with `configure`.\n\n    By using the constructor as the factory method, the interface\n    looks like a normal class, `isinstance` works as usual, etc.  This\n    pattern is most useful when the choice of implementation is likely\n    to be a global decision (e.g. when `~select.epoll` is available,\n    always use it instead of `~select.select`), or when a\n    previously-monolithic class has been split into specialized\n    subclasses.\n\n    Configurable subclasses must define the class methods\n    `configurable_base` and `configurable_default`, and use the instance\n    method `initialize` instead of ``__init__``.\n    \"\"\"\n    __impl_class = None\n    __impl_kwargs = None\n\n    def __new__(cls, *args, **kwargs):\n        base = cls.configurable_base()\n        init_kwargs = {}\n        if cls is base:\n            impl = cls.configured_class()\n            if base.__impl_kwargs:\n                init_kwargs.update(base.__impl_kwargs)\n        else:\n            impl = cls\n        init_kwargs.update(kwargs)\n        instance = super(Configurable, cls).__new__(impl)\n        # initialize vs __init__ chosen for compatibility with AsyncHTTPClient\n        # singleton magic.  If we get rid of that we can switch to __init__\n        # here too.\n        instance.initialize(*args, **init_kwargs)\n        return instance\n\n    @classmethod\n    def configurable_base(cls):\n        \"\"\"Returns the base class of a configurable hierarchy.\n\n        This will normally return the class in which it is defined.\n        (which is *not* necessarily the same as the cls classmethod parameter).\n        \"\"\"\n        raise NotImplementedError()\n\n    @classmethod\n    def configurable_default(cls):\n        \"\"\"Returns the implementation class to be used if none is configured.\"\"\"\n        raise NotImplementedError()\n\n    def initialize(self):\n        \"\"\"Initialize a `Configurable` subclass instance.\n\n        Configurable classes should use `initialize` instead of ``__init__``.\n\n        .. versionchanged:: 4.2\n           Now accepts positional arguments in addition to keyword arguments.\n        \"\"\"\n\n    @classmethod\n    def configure(cls, impl, **kwargs):\n        \"\"\"Sets the class to use when the base class is instantiated.\n\n        Keyword arguments will be saved and added to the arguments passed\n        to the constructor.  This can be used to set global defaults for\n        some parameters.\n        \"\"\"\n        base = cls.configurable_base()\n        if isinstance(impl, (unicode_type, bytes)):\n            impl = import_object(impl)\n        if impl is not None and not issubclass(impl, cls):\n            raise ValueError(\"Invalid subclass of %s\" % cls)\n        base.__impl_class = impl\n        base.__impl_kwargs = kwargs\n\n    @classmethod\n    def configured_class(cls):\n        \"\"\"Returns the currently configured class.\"\"\"\n        base = cls.configurable_base()\n        if cls.__impl_class is None:\n            base.__impl_class = cls.configurable_default()\n        return base.__impl_class\n\n    @classmethod\n    def _save_configuration(cls):\n        base = cls.configurable_base()\n        return (base.__impl_class, base.__impl_kwargs)\n\n    @classmethod\n    def _restore_configuration(cls, saved):\n        base = cls.configurable_base()\n        base.__impl_class = saved[0]\n        base.__impl_kwargs = saved[1]\n\n\nclass ArgReplacer(object):\n    \"\"\"Replaces one value in an ``args, kwargs`` pair.\n\n    Inspects the function signature to find an argument by name\n    whether it is passed by position or keyword.  For use in decorators\n    and similar wrappers.\n    \"\"\"\n    def __init__(self, func, name):\n        self.name = name\n        try:\n            self.arg_pos = self._getargnames(func).index(name)\n        except ValueError:\n            # Not a positional parameter\n            self.arg_pos = None\n\n    def _getargnames(self, func):\n        try:\n            return getargspec(func).args\n        except TypeError:\n            if hasattr(func, 'func_code'):\n                # Cython-generated code has all the attributes needed\n                # by inspect.getargspec, but the inspect module only\n                # works with ordinary functions. Inline the portion of\n                # getargspec that we need here. Note that for static\n                # functions the @cython.binding(True) decorator must\n                # be used (for methods it works out of the box).\n                code = func.func_code\n                return code.co_varnames[:code.co_argcount]\n            raise\n\n    def get_old_value(self, args, kwargs, default=None):\n        \"\"\"Returns the old value of the named argument without replacing it.\n\n        Returns ``default`` if the argument is not present.\n        \"\"\"\n        if self.arg_pos is not None and len(args) > self.arg_pos:\n            return args[self.arg_pos]\n        else:\n            return kwargs.get(self.name, default)\n\n    def replace(self, new_value, args, kwargs):\n        \"\"\"Replace the named argument in ``args, kwargs`` with ``new_value``.\n\n        Returns ``(old_value, args, kwargs)``.  The returned ``args`` and\n        ``kwargs`` objects may not be the same as the input objects, or\n        the input objects may be mutated.\n\n        If the named argument was not found, ``new_value`` will be added\n        to ``kwargs`` and None will be returned as ``old_value``.\n        \"\"\"\n        if self.arg_pos is not None and len(args) > self.arg_pos:\n            # The arg to replace is passed positionally\n            old_value = args[self.arg_pos]\n            args = list(args)  # *args is normally a tuple\n            args[self.arg_pos] = new_value\n        else:\n            # The arg to replace is either omitted or passed by keyword.\n            old_value = kwargs.get(self.name)\n            kwargs[self.name] = new_value\n        return old_value, args, kwargs\n\n\ndef timedelta_to_seconds(td):\n    \"\"\"Equivalent to td.total_seconds() (introduced in python 2.7).\"\"\"\n    return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 ** 6) / float(10 ** 6)\n\n\ndef _websocket_mask_python(mask, data):\n    \"\"\"Websocket masking function.\n\n    `mask` is a `bytes` object of length 4; `data` is a `bytes` object of any length.\n    Returns a `bytes` object of the same length as `data` with the mask applied\n    as specified in section 5.3 of RFC 6455.\n\n    This pure-python implementation may be replaced by an optimized version when available.\n    \"\"\"\n    mask = array.array(\"B\", mask)\n    unmasked = array.array(\"B\", data)\n    for i in xrange(len(data)):\n        unmasked[i] = unmasked[i] ^ mask[i % 4]\n    if hasattr(unmasked, 'tobytes'):\n        # tostring was deprecated in py32.  It hasn't been removed,\n        # but since we turn on deprecation warnings in our tests\n        # we need to use the right one.\n        return unmasked.tobytes()\n    else:\n        return unmasked.tostring()\n\nif (os.environ.get('TORNADO_NO_EXTENSION') or\n        os.environ.get('TORNADO_EXTENSION') == '0'):\n    # These environment variables exist to make it easier to do performance\n    # comparisons; they are not guaranteed to remain supported in the future.\n    _websocket_mask = _websocket_mask_python\nelse:\n    try:\n        from tornado.speedups import websocket_mask as _websocket_mask\n    except ImportError:\n        if os.environ.get('TORNADO_EXTENSION') == '1':\n            raise\n        _websocket_mask = _websocket_mask_python\n\n\ndef doctests():\n    import doctest\n    return doctest.DocTestSuite()\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:** `re_unescape` Does Not Raise `ValueError` for Invalid Escape Sequences

**Description:**
The `re_unescape` function is expected to raise a `ValueError` when it encounters invalid escape sequences. However, when provided with inputs like `'\\d'`, `'\\b'`, or `'\\Z'`, the function does not raise the necessary exceptions. This allows invalid escape sequences to be processed incorrectly, which can lead to unexpected behavior in the application.

**Example Buggy Code:**
```python
def test_re_unescape_invalid_sequences():
    re_unescape('\\d')  # Expected to raise ValueError
    re_unescape('\\b')  # Expected to raise ValueError
    re_unescape('\\Z')  # Expected to raise ValueError
```

**Expected Behavior:**
When `re_unescape` receives an invalid escape sequence such as `'\\d'`, `'\\b'`, or `'\\Z'`, it should raise a `ValueError` to indicate that the input is invalid and cannot be unescaped properly.

**Actual Behavior:**
The `re_unescape` function does not raise any errors when provided with invalid escape sequences. Instead, it processes the input without signaling any issues, allowing potentially malformed data to pass through unchecked.

[/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/util.py
"""Miscellaneous utility functions and classes.

This module is used internally by Tornado.  It is not necessarily expected
that the functions and classes defined here will be useful to other
applications, but they are documented here in case they are.

The one public-facing part of this module is the `Configurable` class
and its `~Configurable.configure` method, which becomes a part of the
interface of its subclasses, including `.AsyncHTTPClient`, `.IOLoop`,
and `.Resolver`.
"""

from __future__ import absolute_import, division, print_function, with_statement

import array
import os
import re
import sys
import zlib


try:
    xrange  # py2
except NameError:
    xrange = range  # py3

# inspect.getargspec() raises DeprecationWarnings in Python 3.5.
# The two functions have compatible interfaces for the parts we need.
try:
    from inspect import getfullargspec as getargspec  # py3
except ImportError:
    from inspect import getargspec  # py2


class ObjectDict(dict):
    """Makes a dictionary behave like an object, with attribute-style access.
    """
    def __getattr__(self, name):
        try:
            return self[name]
        except KeyError:
            raise AttributeError(name)

    def __setattr__(self, name, value):
        self[name] = value


class GzipDecompressor(object):
    """Streaming gzip decompressor.

    The interface is like that of `zlib.decompressobj` (without some of the
    optional arguments, but it understands gzip headers and checksums.
    """
    def __init__(self):
        # Magic parameter makes zlib module understand gzip header
        # http://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib
        # This works on cpython and pypy, but not jython.
        self.decompressobj = zlib.decompressobj(16 + zlib.MAX_WBITS)

    def decompress(self, value, max_length=None):
        """Decompress a chunk, returning newly-available data.

        Some data may be buffered for later processing; `flush` must
        be called when there is no more input data to ensure that
        all data was processed.

        If ``max_length`` is given, some input data may be left over
        in ``unconsumed_tail``; you must retrieve this value and pass
        it back to a future call to `decompress` if it is not empty.
        """
        return self.decompressobj.decompress(value, max_length)

    @property
    def unconsumed_tail(self):
        """Returns the unconsumed portion left over
        """
        return self.decompressobj.unconsumed_tail

    def flush(self):
        """Return any remaining buffered data not yet returned by decompress.

        Also checks for errors such as truncated input.
        No other methods may be called on this object after `flush`.
        """
        return self.decompressobj.flush()


if not isinstance(b'', type('')):
    unicode_type = str
    basestring_type = str
else:
    # These names don't exist in py3, so use noqa comments to disable
    # warnings in flake8.
    unicode_type = unicode  # noqa
    basestring_type = basestring  # noqa


def import_object(name):
    """Imports an object by name.

    import_object('x') is equivalent to 'import x'.
    import_object('x.y.z') is equivalent to 'from x.y import z'.

    >>> import tornado.escape
    >>> import_object('tornado.escape') is tornado.escape
    True
    >>> import_object('tornado.escape.utf8') is tornado.escape.utf8
    True
    >>> import_object('tornado') is tornado
    True
    >>> import_object('tornado.missing_module')
    Traceback (most recent call last):
        ...
    ImportError: No module named missing_module
    """
    if isinstance(name, unicode_type) and str is not unicode_type:
        # On python 2 a byte string is required.
        name = name.encode('utf-8')
    if name.count('.') == 0:
        return __import__(name, None, None)

    parts = name.split('.')
    obj = __import__('.'.join(parts[:-1]), None, None, [parts[-1]], 0)
    try:
        return getattr(obj, parts[-1])
    except AttributeError:
        raise ImportError("No module named %s" % parts[-1])


# Deprecated alias that was used before we dropped py25 support.
# Left here in case anyone outside Tornado is using it.
bytes_type = bytes

if sys.version_info > (3,):
    exec("""
def raise_exc_info(exc_info):
    raise exc_info[1].with_traceback(exc_info[2])

def exec_in(code, glob, loc=None):
    if isinstance(code, str):
        code = compile(code, '<string>', 'exec', dont_inherit=True)
    exec(code, glob, loc)
""")
else:
    exec("""
def raise_exc_info(exc_info):
    raise exc_info[0], exc_info[1], exc_info[2]

def exec_in(code, glob, loc=None):
    if isinstance(code, basestring):
        # exec(string) inherits the caller's future imports; compile
        # the string first to prevent that.
        code = compile(code, '<string>', 'exec', dont_inherit=True)
    exec code in glob, loc
""")


def errno_from_exception(e):
    """Provides the errno from an Exception object.

    There are cases that the errno attribute was not set so we pull
    the errno out of the args but if someone instantiates an Exception
    without any args you will get a tuple error. So this function
    abstracts all that behavior to give you a safe way to get the
    errno.
    """

    if hasattr(e, 'errno'):
        return e.errno
    elif e.args:
        return e.args[0]
    else:
        return None


_re_unescape_split_pattern = re.compile(r'(\\[^0])')
# re.escape('\x00') is a special case

def re_unescape(s):
    '''
    unescape a string escaped by ``re.escape()``
    '''
    parts = []
    for i, splited in enumerate(_re_unescape_split_pattern.split(s)):
        if i % 2:
            parts.append(splited[1])
        else:
            parts.append(splited.replace(r'\000', '\000'))
    return ''.join(parts)


class Configurable(object):
    """Base class for configurable interfaces.

    A configurable interface is an (abstract) class whose constructor
    acts as a factory function for one of its implementation subclasses.
    The implementation subclass as well as optional keyword arguments to
    its initializer can be set globally at runtime with `configure`.

    By using the constructor as the factory method, the interface
    looks like a normal class, `isinstance` works as usual, etc.  This
    pattern is most useful when the choice of implementation is likely
    to be a global decision (e.g. when `~select.epoll` is available,
    always use it instead of `~select.select`), or when a
    previously-monolithic class has been split into specialized
    subclasses.

    Configurable subclasses must define the class methods
    `configurable_base` and `configurable_default`, and use the instance
    method `initialize` instead of ``__init__``.
    """
    __impl_class = None
    __impl_kwargs = None

    def __new__(cls, *args, **kwargs):
        base = cls.configurable_base()
        init_kwargs = {}
        if cls is base:
            impl = cls.configured_class()
            if base.__impl_kwargs:
                init_kwargs.update(base.__impl_kwargs)
        else:
            impl = cls
        init_kwargs.update(kwargs)
        instance = super(Configurable, cls).__new__(impl)
        # initialize vs __init__ chosen for compatibility with AsyncHTTPClient
        # singleton magic.  If we get rid of that we can switch to __init__
        # here too.
        instance.initialize(*args, **init_kwargs)
        return instance

    @classmethod
    def configurable_base(cls):
        """Returns the base class of a configurable hierarchy.

        This will normally return the class in which it is defined.
        (which is *not* necessarily the same as the cls classmethod parameter).
        """
        raise NotImplementedError()

    @classmethod
    def configurable_default(cls):
        """Returns the implementation class to be used if none is configured."""
        raise NotImplementedError()

    def initialize(self):
        """Initialize a `Configurable` subclass instance.

        Configurable classes should use `initialize` instead of ``__init__``.

        .. versionchanged:: 4.2
           Now accepts positional arguments in addition to keyword arguments.
        """

    @classmethod
    def configure(cls, impl, **kwargs):
        """Sets the class to use when the base class is instantiated.

        Keyword arguments will be saved and added to the arguments passed
        to the constructor.  This can be used to set global defaults for
        some parameters.
        """
        base = cls.configurable_base()
        if isinstance(impl, (unicode_type, bytes)):
            impl = import_object(impl)
        if impl is not None and not issubclass(impl, cls):
            raise ValueError("Invalid subclass of %s" % cls)
        base.__impl_class = impl
        base.__impl_kwargs = kwargs

    @classmethod
    def configured_class(cls):
        """Returns the currently configured class."""
        base = cls.configurable_base()
        if cls.__impl_class is None:
            base.__impl_class = cls.configurable_default()
        return base.__impl_class

    @classmethod
    def _save_configuration(cls):
        base = cls.configurable_base()
        return (base.__impl_class, base.__impl_kwargs)

    @classmethod
    def _restore_configuration(cls, saved):
        base = cls.configurable_base()
        base.__impl_class = saved[0]
        base.__impl_kwargs = saved[1]


class ArgReplacer(object):
    """Replaces one value in an ``args, kwargs`` pair.

    Inspects the function signature to find an argument by name
    whether it is passed by position or keyword.  For use in decorators
    and similar wrappers.
    """
    def __init__(self, func, name):
        self.name = name
        try:
            self.arg_pos = self._getargnames(func).index(name)
        except ValueError:
            # Not a positional parameter
            self.arg_pos = None

    def _getargnames(self, func):
        try:
            return getargspec(func).args
        except TypeError:
            if hasattr(func, 'func_code'):
                # Cython-generated code has all the attributes needed
                # by inspect.getargspec, but the inspect module only
                # works with ordinary functions. Inline the portion of
                # getargspec that we need here. Note that for static
                # functions the @cython.binding(True) decorator must
                # be used (for methods it works out of the box).
                code = func.func_code
                return code.co_varnames[:code.co_argcount]
            raise

    def get_old_value(self, args, kwargs, default=None):
        """Returns the old value of the named argument without replacing it.

        Returns ``default`` if the argument is not present.
        """
        if self.arg_pos is not None and len(args) > self.arg_pos:
            return args[self.arg_pos]
        else:
            return kwargs.get(self.name, default)

    def replace(self, new_value, args, kwargs):
        """Replace the named argument in ``args, kwargs`` with ``new_value``.

        Returns ``(old_value, args, kwargs)``.  The returned ``args`` and
        ``kwargs`` objects may not be the same as the input objects, or
        the input objects may be mutated.

        If the named argument was not found, ``new_value`` will be added
        to ``kwargs`` and None will be returned as ``old_value``.
        """
        if self.arg_pos is not None and len(args) > self.arg_pos:
            # The arg to replace is passed positionally
            old_value = args[self.arg_pos]
            args = list(args)  # *args is normally a tuple
            args[self.arg_pos] = new_value
        else:
            # The arg to replace is either omitted or passed by keyword.
            old_value = kwargs.get(self.name)
            kwargs[self.name] = new_value
        return old_value, args, kwargs


def timedelta_to_seconds(td):
    """Equivalent to td.total_seconds() (introduced in python 2.7)."""
    return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 ** 6) / float(10 ** 6)


def _websocket_mask_python(mask, data):
    """Websocket masking function.

    `mask` is a `bytes` object of length 4; `data` is a `bytes` object of any length.
    Returns a `bytes` object of the same length as `data` with the mask applied
    as specified in section 5.3 of RFC 6455.

    This pure-python implementation may be replaced by an optimized version when available.
    """
    mask = array.array("B", mask)
    unmasked = array.array("B", data)
    for i in xrange(len(data)):
        unmasked[i] = unmasked[i] ^ mask[i % 4]
    if hasattr(unmasked, 'tobytes'):
        # tostring was deprecated in py32.  It hasn't been removed,
        # but since we turn on deprecation warnings in our tests
        # we need to use the right one.
        return unmasked.tobytes()
    else:
        return unmasked.tostring()

if (os.environ.get('TORNADO_NO_EXTENSION') or
        os.environ.get('TORNADO_EXTENSION') == '0'):
    # These environment variables exist to make it easier to do performance
    # comparisons; they are not guaranteed to remain supported in the future.
    _websocket_mask = _websocket_mask_python
else:
    try:
        from tornado.speedups import websocket_mask as _websocket_mask
    except ImportError:
        if os.environ.get('TORNADO_EXTENSION') == '1':
            raise
        _websocket_mask = _websocket_mask_python


def doctests():
    import doctest
    return doctest.DocTestSuite()

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