')\n html = html[:sloc] + utf8(js) + b'\\n' + html[sloc:]\n if js_embed:\n js = b''\n sloc = html.rindex(b'')\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(''\n for p in paths)\n hloc = html.index(b'')\n html = html[:hloc] + utf8(css) + b'\\n' + html[hloc:]\n if css_embed:\n css = b''\n hloc = html.index(b'')\n html = html[:hloc] + css + b'\\n' + html[hloc:]\n if html_heads:\n hloc = html.index(b'')\n html = html[:hloc] + b''.join(html_heads) + b'\\n' + html[hloc:]\n if html_bodies:\n hloc = html.index(b'')\n html = html[:hloc] + b''.join(html_bodies) + b'\\n' + html[hloc:]\n self.finish(html)\n\n def render_string(self, template_name, **kwargs):\n \"\"\"Generate the given template with the given arguments.\n\n We return the generated byte string (in utf8). To generate and\n write a template as a response, use render() above.\n \"\"\"\n # If no template_path is specified, use the path of the calling file\n template_path = self.get_template_path()\n if not template_path:\n frame = sys._getframe(0)\n web_file = frame.f_code.co_filename\n while frame.f_code.co_filename == web_file:\n frame = frame.f_back\n template_path = os.path.dirname(frame.f_code.co_filename)\n with RequestHandler._template_loader_lock:\n if template_path not in RequestHandler._template_loaders:\n loader = self.create_template_loader(template_path)\n RequestHandler._template_loaders[template_path] = loader\n else:\n loader = RequestHandler._template_loaders[template_path]\n t = loader.load(template_name)\n namespace = self.get_template_namespace()\n namespace.update(kwargs)\n return t.generate(**namespace)\n\n def get_template_namespace(self):\n \"\"\"Returns a dictionary to be used as the default template namespace.\n\n May be overridden by subclasses to add or modify values.\n\n The results of this method will be combined with additional\n defaults in the `tornado.template` module and keyword arguments\n to `render` or `render_string`.\n \"\"\"\n namespace = dict(\n handler=self,\n request=self.request,\n current_user=self.current_user,\n locale=self.locale,\n _=self.locale.translate,\n static_url=self.static_url,\n xsrf_form_html=self.xsrf_form_html,\n reverse_url=self.reverse_url\n )\n namespace.update(self.ui)\n return namespace\n\n def create_template_loader(self, template_path):\n \"\"\"Returns a new template loader for the given path.\n\n May be overridden by subclasses. By default returns a\n directory-based loader on the given path, using the\n ``autoescape`` application setting. If a ``template_loader``\n application setting is supplied, uses that instead.\n \"\"\"\n settings = self.application.settings\n if \"template_loader\" in settings:\n return settings[\"template_loader\"]\n kwargs = {}\n if \"autoescape\" in settings:\n # autoescape=None means \"no escaping\", so we have to be sure\n # to only pass this kwarg if the user asked for it.\n kwargs[\"autoescape\"] = settings[\"autoescape\"]\n return template.Loader(template_path, **kwargs)\n\n def flush(self, include_footers=False, callback=None):\n \"\"\"Flushes the current output buffer to the network.\n\n The ``callback`` argument, if given, can be used for flow control:\n it will be run when all flushed data has been written to the socket.\n Note that only one flush callback can be outstanding at a time;\n if another flush occurs before the previous flush's callback\n has been run, the previous callback will be discarded.\n\n .. 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, 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(self.request.version,\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. May be caused \"\n \"by using async operations without the \"\n \"@asynchronous decorator.\")\n\n if chunk is not None:\n self.write(chunk)\n\n # Automatically support ETags and add the Content-Length header if\n # we have not flushed any content yet.\n if not self._headers_written:\n if (self._status_code == 200 and\n self.request.method in (\"GET\", \"HEAD\") and\n \"Etag\" not in self._headers):\n self.set_etag_header()\n if self.check_etag_header():\n self._write_buffer = []\n self.set_status(304)\n if self._status_code == 304:\n assert not self._write_buffer, \"Cannot send body with 304\"\n self._clear_headers_for_304()\n elif \"Content-Length\" not in self._headers:\n content_length = sum(len(part) for part in self._write_buffer)\n self.set_header(\"Content-Length\", content_length)\n\n if hasattr(self.request, \"connection\"):\n # Now that the request is finished, clear the callback we\n # set on the 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 self.finish()\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(\"
\"\n \"