Writes the given chunk to the output buffer. To write the output to the network, use the `flush()` method below. If the given chunk is a dictionary, we write it as JSON and set the Content-Type of the response to be ``application/json``. (if you want to send JSON as
(self, chunk: Union[str, bytes, dict])
| 976 | self.finish() |
| 977 | |
| 978 | def write(self, chunk: Union[str, bytes, dict]) -> None: |
| 979 | """Writes the given chunk to the output buffer. |
| 980 | |
| 981 | To write the output to the network, use the `flush()` method below. |
| 982 | |
| 983 | If the given chunk is a dictionary, we write it as JSON and set |
| 984 | the Content-Type of the response to be ``application/json``. |
| 985 | (if you want to send JSON as a different ``Content-Type``, call |
| 986 | ``set_header`` *after* calling ``write()``). |
| 987 | |
| 988 | Note that lists are not converted to JSON because of a potential |
| 989 | cross-site security vulnerability. All JSON output should be |
| 990 | wrapped in a dictionary. More details at |
| 991 | http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ and |
| 992 | https://github.com/facebook/tornado/issues/1009 |
| 993 | """ |
| 994 | if self._finished: |
| 995 | raise RuntimeError("Cannot write() after finish()") |
| 996 | if not isinstance(chunk, (bytes, unicode_type, dict)): |
| 997 | message = "write() only accepts bytes, unicode, and dict objects" |
| 998 | if isinstance(chunk, list): |
| 999 | message += ( |
| 1000 | ". Lists not accepted for security reasons; see " |
| 1001 | + "http://www.tornadoweb.org/en/stable/web.html#tornado.web.RequestHandler.write" # noqa: E501 |
| 1002 | ) |
| 1003 | raise TypeError(message) |
| 1004 | if isinstance(chunk, dict): |
| 1005 | chunk = escape.json_encode(chunk) |
| 1006 | self.set_header("Content-Type", "application/json; charset=UTF-8") |
| 1007 | chunk = utf8(chunk) |
| 1008 | self._write_buffer.append(chunk) |
| 1009 | |
| 1010 | def render(self, template_name: str, **kwargs: Any) -> "Future[None]": |
| 1011 | """Renders the template with the given arguments as the response. |