web.py 135 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593
  1. #
  2. # Copyright 2009 Facebook
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  5. # not use this file except in compliance with the License. You may obtain
  6. # a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. # License for the specific language governing permissions and limitations
  14. # under the License.
  15. """``tornado.web`` provides a simple web framework with asynchronous
  16. features that allow it to scale to large numbers of open connections,
  17. making it ideal for `long polling
  18. <http://en.wikipedia.org/wiki/Push_technology#Long_polling>`_.
  19. Here is a simple "Hello, world" example app:
  20. .. testcode::
  21. import tornado.ioloop
  22. import tornado.web
  23. class MainHandler(tornado.web.RequestHandler):
  24. def get(self):
  25. self.write("Hello, world")
  26. if __name__ == "__main__":
  27. application = tornado.web.Application([
  28. (r"/", MainHandler),
  29. ])
  30. application.listen(8888)
  31. tornado.ioloop.IOLoop.current().start()
  32. .. testoutput::
  33. :hide:
  34. See the :doc:`guide` for additional information.
  35. Thread-safety notes
  36. -------------------
  37. In general, methods on `RequestHandler` and elsewhere in Tornado are
  38. not thread-safe. In particular, methods such as
  39. `~RequestHandler.write()`, `~RequestHandler.finish()`, and
  40. `~RequestHandler.flush()` must only be called from the main thread. If
  41. you use multiple threads it is important to use `.IOLoop.add_callback`
  42. to transfer control back to the main thread before finishing the
  43. request, or to limit your use of other threads to
  44. `.IOLoop.run_in_executor` and ensure that your callbacks running in
  45. the executor do not refer to Tornado objects.
  46. """
  47. import base64
  48. import binascii
  49. import datetime
  50. import email.utils
  51. import functools
  52. import gzip
  53. import hashlib
  54. import hmac
  55. import http.cookies
  56. from inspect import isclass
  57. from io import BytesIO
  58. import mimetypes
  59. import numbers
  60. import os.path
  61. import re
  62. import sys
  63. import threading
  64. import time
  65. import tornado
  66. import traceback
  67. import types
  68. import urllib.parse
  69. from urllib.parse import urlencode
  70. from tornado.concurrent import Future, future_set_result_unless_cancelled
  71. from tornado import escape
  72. from tornado import gen
  73. from tornado.httpserver import HTTPServer
  74. from tornado import httputil
  75. from tornado import iostream
  76. import tornado.locale
  77. from tornado import locale
  78. from tornado.log import access_log, app_log, gen_log
  79. from tornado import template
  80. from tornado.escape import utf8, _unicode
  81. from tornado.routing import (
  82. AnyMatches,
  83. DefaultHostMatches,
  84. HostMatches,
  85. ReversibleRouter,
  86. Rule,
  87. ReversibleRuleRouter,
  88. URLSpec,
  89. _RuleList,
  90. )
  91. from tornado.util import ObjectDict, unicode_type, _websocket_mask
  92. url = URLSpec
  93. from typing import (
  94. Dict,
  95. Any,
  96. Union,
  97. Optional,
  98. Awaitable,
  99. Tuple,
  100. List,
  101. Callable,
  102. Iterable,
  103. Generator,
  104. Type,
  105. cast,
  106. overload,
  107. )
  108. from types import TracebackType
  109. import typing
  110. if typing.TYPE_CHECKING:
  111. from typing import Set # noqa: F401
  112. # The following types are accepted by RequestHandler.set_header
  113. # and related methods.
  114. _HeaderTypes = Union[bytes, unicode_type, int, numbers.Integral, datetime.datetime]
  115. _CookieSecretTypes = Union[str, bytes, Dict[int, str], Dict[int, bytes]]
  116. MIN_SUPPORTED_SIGNED_VALUE_VERSION = 1
  117. """The oldest signed value version supported by this version of Tornado.
  118. Signed values older than this version cannot be decoded.
  119. .. versionadded:: 3.2.1
  120. """
  121. MAX_SUPPORTED_SIGNED_VALUE_VERSION = 2
  122. """The newest signed value version supported by this version of Tornado.
  123. Signed values newer than this version cannot be decoded.
  124. .. versionadded:: 3.2.1
  125. """
  126. DEFAULT_SIGNED_VALUE_VERSION = 2
  127. """The signed value version produced by `.RequestHandler.create_signed_value`.
  128. May be overridden by passing a ``version`` keyword argument.
  129. .. versionadded:: 3.2.1
  130. """
  131. DEFAULT_SIGNED_VALUE_MIN_VERSION = 1
  132. """The oldest signed value accepted by `.RequestHandler.get_secure_cookie`.
  133. May be overridden by passing a ``min_version`` keyword argument.
  134. .. versionadded:: 3.2.1
  135. """
  136. class _ArgDefaultMarker:
  137. pass
  138. _ARG_DEFAULT = _ArgDefaultMarker()
  139. class RequestHandler(object):
  140. """Base class for HTTP request handlers.
  141. Subclasses must define at least one of the methods defined in the
  142. "Entry points" section below.
  143. Applications should not construct `RequestHandler` objects
  144. directly and subclasses should not override ``__init__`` (override
  145. `~RequestHandler.initialize` instead).
  146. """
  147. SUPPORTED_METHODS = ("GET", "HEAD", "POST", "DELETE", "PATCH", "PUT", "OPTIONS")
  148. _template_loaders = {} # type: Dict[str, template.BaseLoader]
  149. _template_loader_lock = threading.Lock()
  150. _remove_control_chars_regex = re.compile(r"[\x00-\x08\x0e-\x1f]")
  151. _stream_request_body = False
  152. # Will be set in _execute.
  153. _transforms = None # type: List[OutputTransform]
  154. path_args = None # type: List[str]
  155. path_kwargs = None # type: Dict[str, str]
  156. def __init__(
  157. self,
  158. application: "Application",
  159. request: httputil.HTTPServerRequest,
  160. **kwargs: Any
  161. ) -> None:
  162. super(RequestHandler, self).__init__()
  163. self.application = application
  164. self.request = request
  165. self._headers_written = False
  166. self._finished = False
  167. self._auto_finish = True
  168. self._prepared_future = None
  169. self.ui = ObjectDict(
  170. (n, self._ui_method(m)) for n, m in application.ui_methods.items()
  171. )
  172. # UIModules are available as both `modules` and `_tt_modules` in the
  173. # template namespace. Historically only `modules` was available
  174. # but could be clobbered by user additions to the namespace.
  175. # The template {% module %} directive looks in `_tt_modules` to avoid
  176. # possible conflicts.
  177. self.ui["_tt_modules"] = _UIModuleNamespace(self, application.ui_modules)
  178. self.ui["modules"] = self.ui["_tt_modules"]
  179. self.clear()
  180. assert self.request.connection is not None
  181. # TODO: need to add set_close_callback to HTTPConnection interface
  182. self.request.connection.set_close_callback( # type: ignore
  183. self.on_connection_close
  184. )
  185. self.initialize(**kwargs) # type: ignore
  186. def _initialize(self) -> None:
  187. pass
  188. initialize = _initialize # type: Callable[..., None]
  189. """Hook for subclass initialization. Called for each request.
  190. A dictionary passed as the third argument of a ``URLSpec`` will be
  191. supplied as keyword arguments to ``initialize()``.
  192. Example::
  193. class ProfileHandler(RequestHandler):
  194. def initialize(self, database):
  195. self.database = database
  196. def get(self, username):
  197. ...
  198. app = Application([
  199. (r'/user/(.*)', ProfileHandler, dict(database=database)),
  200. ])
  201. """
  202. @property
  203. def settings(self) -> Dict[str, Any]:
  204. """An alias for `self.application.settings <Application.settings>`."""
  205. return self.application.settings
  206. def _unimplemented_method(self, *args: str, **kwargs: str) -> None:
  207. raise HTTPError(405)
  208. head = _unimplemented_method # type: Callable[..., Optional[Awaitable[None]]]
  209. get = _unimplemented_method # type: Callable[..., Optional[Awaitable[None]]]
  210. post = _unimplemented_method # type: Callable[..., Optional[Awaitable[None]]]
  211. delete = _unimplemented_method # type: Callable[..., Optional[Awaitable[None]]]
  212. patch = _unimplemented_method # type: Callable[..., Optional[Awaitable[None]]]
  213. put = _unimplemented_method # type: Callable[..., Optional[Awaitable[None]]]
  214. options = _unimplemented_method # type: Callable[..., Optional[Awaitable[None]]]
  215. def prepare(self) -> Optional[Awaitable[None]]:
  216. """Called at the beginning of a request before `get`/`post`/etc.
  217. Override this method to perform common initialization regardless
  218. of the request method.
  219. Asynchronous support: Use ``async def`` or decorate this method with
  220. `.gen.coroutine` to make it asynchronous.
  221. If this method returns an ``Awaitable`` execution will not proceed
  222. until the ``Awaitable`` is done.
  223. .. versionadded:: 3.1
  224. Asynchronous support.
  225. """
  226. pass
  227. def on_finish(self) -> None:
  228. """Called after the end of a request.
  229. Override this method to perform cleanup, logging, etc.
  230. This method is a counterpart to `prepare`. ``on_finish`` may
  231. not produce any output, as it is called after the response
  232. has been sent to the client.
  233. """
  234. pass
  235. def on_connection_close(self) -> None:
  236. """Called in async handlers if the client closed the connection.
  237. Override this to clean up resources associated with
  238. long-lived connections. Note that this method is called only if
  239. the connection was closed during asynchronous processing; if you
  240. need to do cleanup after every request override `on_finish`
  241. instead.
  242. Proxies may keep a connection open for a time (perhaps
  243. indefinitely) after the client has gone away, so this method
  244. may not be called promptly after the end user closes their
  245. connection.
  246. """
  247. if _has_stream_request_body(self.__class__):
  248. if not self.request._body_future.done():
  249. self.request._body_future.set_exception(iostream.StreamClosedError())
  250. self.request._body_future.exception()
  251. def clear(self) -> None:
  252. """Resets all headers and content for this response."""
  253. self._headers = httputil.HTTPHeaders(
  254. {
  255. "Server": "TornadoServer/%s" % tornado.version,
  256. "Content-Type": "text/html; charset=UTF-8",
  257. "Date": httputil.format_timestamp(time.time()),
  258. }
  259. )
  260. self.set_default_headers()
  261. self._write_buffer = [] # type: List[bytes]
  262. self._status_code = 200
  263. self._reason = httputil.responses[200]
  264. def set_default_headers(self) -> None:
  265. """Override this to set HTTP headers at the beginning of the request.
  266. For example, this is the place to set a custom ``Server`` header.
  267. Note that setting such headers in the normal flow of request
  268. processing may not do what you want, since headers may be reset
  269. during error handling.
  270. """
  271. pass
  272. def set_status(self, status_code: int, reason: str = None) -> None:
  273. """Sets the status code for our response.
  274. :arg int status_code: Response status code.
  275. :arg str reason: Human-readable reason phrase describing the status
  276. code. If ``None``, it will be filled in from
  277. `http.client.responses` or "Unknown".
  278. .. versionchanged:: 5.0
  279. No longer validates that the response code is in
  280. `http.client.responses`.
  281. """
  282. self._status_code = status_code
  283. if reason is not None:
  284. self._reason = escape.native_str(reason)
  285. else:
  286. self._reason = httputil.responses.get(status_code, "Unknown")
  287. def get_status(self) -> int:
  288. """Returns the status code for our response."""
  289. return self._status_code
  290. def set_header(self, name: str, value: _HeaderTypes) -> None:
  291. """Sets the given response header name and value.
  292. All header values are converted to strings (`datetime` objects
  293. are formatted according to the HTTP specification for the
  294. ``Date`` header).
  295. """
  296. self._headers[name] = self._convert_header_value(value)
  297. def add_header(self, name: str, value: _HeaderTypes) -> None:
  298. """Adds the given response header and value.
  299. Unlike `set_header`, `add_header` may be called multiple times
  300. to return multiple values for the same header.
  301. """
  302. self._headers.add(name, self._convert_header_value(value))
  303. def clear_header(self, name: str) -> None:
  304. """Clears an outgoing header, undoing a previous `set_header` call.
  305. Note that this method does not apply to multi-valued headers
  306. set by `add_header`.
  307. """
  308. if name in self._headers:
  309. del self._headers[name]
  310. _INVALID_HEADER_CHAR_RE = re.compile(r"[\x00-\x1f]")
  311. def _convert_header_value(self, value: _HeaderTypes) -> str:
  312. # Convert the input value to a str. This type check is a bit
  313. # subtle: The bytes case only executes on python 3, and the
  314. # unicode case only executes on python 2, because the other
  315. # cases are covered by the first match for str.
  316. if isinstance(value, str):
  317. retval = value
  318. elif isinstance(value, bytes): # py3
  319. # Non-ascii characters in headers are not well supported,
  320. # but if you pass bytes, use latin1 so they pass through as-is.
  321. retval = value.decode("latin1")
  322. elif isinstance(value, unicode_type): # py2
  323. # TODO: This is inconsistent with the use of latin1 above,
  324. # but it's been that way for a long time. Should it change?
  325. retval = escape.utf8(value)
  326. elif isinstance(value, numbers.Integral):
  327. # return immediately since we know the converted value will be safe
  328. return str(value)
  329. elif isinstance(value, datetime.datetime):
  330. return httputil.format_timestamp(value)
  331. else:
  332. raise TypeError("Unsupported header value %r" % value)
  333. # If \n is allowed into the header, it is possible to inject
  334. # additional headers or split the request.
  335. if RequestHandler._INVALID_HEADER_CHAR_RE.search(retval):
  336. raise ValueError("Unsafe header value %r", retval)
  337. return retval
  338. @overload
  339. def get_argument(self, name: str, default: str, strip: bool = True) -> str:
  340. pass
  341. @overload # noqa: F811
  342. def get_argument(
  343. self, name: str, default: _ArgDefaultMarker = _ARG_DEFAULT, strip: bool = True
  344. ) -> str:
  345. pass
  346. @overload # noqa: F811
  347. def get_argument(
  348. self, name: str, default: None, strip: bool = True
  349. ) -> Optional[str]:
  350. pass
  351. def get_argument( # noqa: F811
  352. self,
  353. name: str,
  354. default: Union[None, str, _ArgDefaultMarker] = _ARG_DEFAULT,
  355. strip: bool = True,
  356. ) -> Optional[str]:
  357. """Returns the value of the argument with the given name.
  358. If default is not provided, the argument is considered to be
  359. required, and we raise a `MissingArgumentError` if it is missing.
  360. If the argument appears in the request more than once, we return the
  361. last value.
  362. This method searches both the query and body arguments.
  363. """
  364. return self._get_argument(name, default, self.request.arguments, strip)
  365. def get_arguments(self, name: str, strip: bool = True) -> List[str]:
  366. """Returns a list of the arguments with the given name.
  367. If the argument is not present, returns an empty list.
  368. This method searches both the query and body arguments.
  369. """
  370. # Make sure `get_arguments` isn't accidentally being called with a
  371. # positional argument that's assumed to be a default (like in
  372. # `get_argument`.)
  373. assert isinstance(strip, bool)
  374. return self._get_arguments(name, self.request.arguments, strip)
  375. def get_body_argument(
  376. self,
  377. name: str,
  378. default: Union[None, str, _ArgDefaultMarker] = _ARG_DEFAULT,
  379. strip: bool = True,
  380. ) -> Optional[str]:
  381. """Returns the value of the argument with the given name
  382. from the request body.
  383. If default is not provided, the argument is considered to be
  384. required, and we raise a `MissingArgumentError` if it is missing.
  385. If the argument appears in the url more than once, we return the
  386. last value.
  387. .. versionadded:: 3.2
  388. """
  389. return self._get_argument(name, default, self.request.body_arguments, strip)
  390. def get_body_arguments(self, name: str, strip: bool = True) -> List[str]:
  391. """Returns a list of the body arguments with the given name.
  392. If the argument is not present, returns an empty list.
  393. .. versionadded:: 3.2
  394. """
  395. return self._get_arguments(name, self.request.body_arguments, strip)
  396. def get_query_argument(
  397. self,
  398. name: str,
  399. default: Union[None, str, _ArgDefaultMarker] = _ARG_DEFAULT,
  400. strip: bool = True,
  401. ) -> Optional[str]:
  402. """Returns the value of the argument with the given name
  403. from the request query string.
  404. If default is not provided, the argument is considered to be
  405. required, and we raise a `MissingArgumentError` if it is missing.
  406. If the argument appears in the url more than once, we return the
  407. last value.
  408. .. versionadded:: 3.2
  409. """
  410. return self._get_argument(name, default, self.request.query_arguments, strip)
  411. def get_query_arguments(self, name: str, strip: bool = True) -> List[str]:
  412. """Returns a list of the query arguments with the given name.
  413. If the argument is not present, returns an empty list.
  414. .. versionadded:: 3.2
  415. """
  416. return self._get_arguments(name, self.request.query_arguments, strip)
  417. def _get_argument(
  418. self,
  419. name: str,
  420. default: Union[None, str, _ArgDefaultMarker],
  421. source: Dict[str, List[bytes]],
  422. strip: bool = True,
  423. ) -> Optional[str]:
  424. args = self._get_arguments(name, source, strip=strip)
  425. if not args:
  426. if isinstance(default, _ArgDefaultMarker):
  427. raise MissingArgumentError(name)
  428. return default
  429. return args[-1]
  430. def _get_arguments(
  431. self, name: str, source: Dict[str, List[bytes]], strip: bool = True
  432. ) -> List[str]:
  433. values = []
  434. for v in source.get(name, []):
  435. s = self.decode_argument(v, name=name)
  436. if isinstance(s, unicode_type):
  437. # Get rid of any weird control chars (unless decoding gave
  438. # us bytes, in which case leave it alone)
  439. s = RequestHandler._remove_control_chars_regex.sub(" ", s)
  440. if strip:
  441. s = s.strip()
  442. values.append(s)
  443. return values
  444. def decode_argument(self, value: bytes, name: str = None) -> str:
  445. """Decodes an argument from the request.
  446. The argument has been percent-decoded and is now a byte string.
  447. By default, this method decodes the argument as utf-8 and returns
  448. a unicode string, but this may be overridden in subclasses.
  449. This method is used as a filter for both `get_argument()` and for
  450. values extracted from the url and passed to `get()`/`post()`/etc.
  451. The name of the argument is provided if known, but may be None
  452. (e.g. for unnamed groups in the url regex).
  453. """
  454. try:
  455. return _unicode(value)
  456. except UnicodeDecodeError:
  457. raise HTTPError(
  458. 400, "Invalid unicode in %s: %r" % (name or "url", value[:40])
  459. )
  460. @property
  461. def cookies(self) -> Dict[str, http.cookies.Morsel]:
  462. """An alias for
  463. `self.request.cookies <.httputil.HTTPServerRequest.cookies>`."""
  464. return self.request.cookies
  465. def get_cookie(self, name: str, default: str = None) -> Optional[str]:
  466. """Returns the value of the request cookie with the given name.
  467. If the named cookie is not present, returns ``default``.
  468. This method only returns cookies that were present in the request.
  469. It does not see the outgoing cookies set by `set_cookie` in this
  470. handler.
  471. """
  472. if self.request.cookies is not None and name in self.request.cookies:
  473. return self.request.cookies[name].value
  474. return default
  475. def set_cookie(
  476. self,
  477. name: str,
  478. value: Union[str, bytes],
  479. domain: str = None,
  480. expires: Union[float, Tuple, datetime.datetime] = None,
  481. path: str = "/",
  482. expires_days: int = None,
  483. **kwargs: Any
  484. ) -> None:
  485. """Sets an outgoing cookie name/value with the given options.
  486. Newly-set cookies are not immediately visible via `get_cookie`;
  487. they are not present until the next request.
  488. expires may be a numeric timestamp as returned by `time.time`,
  489. a time tuple as returned by `time.gmtime`, or a
  490. `datetime.datetime` object.
  491. Additional keyword arguments are set on the cookies.Morsel
  492. directly.
  493. See https://docs.python.org/3/library/http.cookies.html#http.cookies.Morsel
  494. for available attributes.
  495. """
  496. # The cookie library only accepts type str, in both python 2 and 3
  497. name = escape.native_str(name)
  498. value = escape.native_str(value)
  499. if re.search(r"[\x00-\x20]", name + value):
  500. # Don't let us accidentally inject bad stuff
  501. raise ValueError("Invalid cookie %r: %r" % (name, value))
  502. if not hasattr(self, "_new_cookie"):
  503. self._new_cookie = http.cookies.SimpleCookie()
  504. if name in self._new_cookie:
  505. del self._new_cookie[name]
  506. self._new_cookie[name] = value
  507. morsel = self._new_cookie[name]
  508. if domain:
  509. morsel["domain"] = domain
  510. if expires_days is not None and not expires:
  511. expires = datetime.datetime.utcnow() + datetime.timedelta(days=expires_days)
  512. if expires:
  513. morsel["expires"] = httputil.format_timestamp(expires)
  514. if path:
  515. morsel["path"] = path
  516. for k, v in kwargs.items():
  517. if k == "max_age":
  518. k = "max-age"
  519. # skip falsy values for httponly and secure flags because
  520. # SimpleCookie sets them regardless
  521. if k in ["httponly", "secure"] and not v:
  522. continue
  523. morsel[k] = v
  524. def clear_cookie(self, name: str, path: str = "/", domain: str = None) -> None:
  525. """Deletes the cookie with the given name.
  526. Due to limitations of the cookie protocol, you must pass the same
  527. path and domain to clear a cookie as were used when that cookie
  528. was set (but there is no way to find out on the server side
  529. which values were used for a given cookie).
  530. Similar to `set_cookie`, the effect of this method will not be
  531. seen until the following request.
  532. """
  533. expires = datetime.datetime.utcnow() - datetime.timedelta(days=365)
  534. self.set_cookie(name, value="", path=path, expires=expires, domain=domain)
  535. def clear_all_cookies(self, path: str = "/", domain: str = None) -> None:
  536. """Deletes all the cookies the user sent with this request.
  537. See `clear_cookie` for more information on the path and domain
  538. parameters.
  539. Similar to `set_cookie`, the effect of this method will not be
  540. seen until the following request.
  541. .. versionchanged:: 3.2
  542. Added the ``path`` and ``domain`` parameters.
  543. """
  544. for name in self.request.cookies:
  545. self.clear_cookie(name, path=path, domain=domain)
  546. def set_secure_cookie(
  547. self,
  548. name: str,
  549. value: Union[str, bytes],
  550. expires_days: int = 30,
  551. version: int = None,
  552. **kwargs: Any
  553. ) -> None:
  554. """Signs and timestamps a cookie so it cannot be forged.
  555. You must specify the ``cookie_secret`` setting in your Application
  556. to use this method. It should be a long, random sequence of bytes
  557. to be used as the HMAC secret for the signature.
  558. To read a cookie set with this method, use `get_secure_cookie()`.
  559. Note that the ``expires_days`` parameter sets the lifetime of the
  560. cookie in the browser, but is independent of the ``max_age_days``
  561. parameter to `get_secure_cookie`.
  562. Secure cookies may contain arbitrary byte values, not just unicode
  563. strings (unlike regular cookies)
  564. Similar to `set_cookie`, the effect of this method will not be
  565. seen until the following request.
  566. .. versionchanged:: 3.2.1
  567. Added the ``version`` argument. Introduced cookie version 2
  568. and made it the default.
  569. """
  570. self.set_cookie(
  571. name,
  572. self.create_signed_value(name, value, version=version),
  573. expires_days=expires_days,
  574. **kwargs
  575. )
  576. def create_signed_value(
  577. self, name: str, value: Union[str, bytes], version: int = None
  578. ) -> bytes:
  579. """Signs and timestamps a string so it cannot be forged.
  580. Normally used via set_secure_cookie, but provided as a separate
  581. method for non-cookie uses. To decode a value not stored
  582. as a cookie use the optional value argument to get_secure_cookie.
  583. .. versionchanged:: 3.2.1
  584. Added the ``version`` argument. Introduced cookie version 2
  585. and made it the default.
  586. """
  587. self.require_setting("cookie_secret", "secure cookies")
  588. secret = self.application.settings["cookie_secret"]
  589. key_version = None
  590. if isinstance(secret, dict):
  591. if self.application.settings.get("key_version") is None:
  592. raise Exception("key_version setting must be used for secret_key dicts")
  593. key_version = self.application.settings["key_version"]
  594. return create_signed_value(
  595. secret, name, value, version=version, key_version=key_version
  596. )
  597. def get_secure_cookie(
  598. self,
  599. name: str,
  600. value: str = None,
  601. max_age_days: int = 31,
  602. min_version: int = None,
  603. ) -> Optional[bytes]:
  604. """Returns the given signed cookie if it validates, or None.
  605. The decoded cookie value is returned as a byte string (unlike
  606. `get_cookie`).
  607. Similar to `get_cookie`, this method only returns cookies that
  608. were present in the request. It does not see outgoing cookies set by
  609. `set_secure_cookie` in this handler.
  610. .. versionchanged:: 3.2.1
  611. Added the ``min_version`` argument. Introduced cookie version 2;
  612. both versions 1 and 2 are accepted by default.
  613. """
  614. self.require_setting("cookie_secret", "secure cookies")
  615. if value is None:
  616. value = self.get_cookie(name)
  617. return decode_signed_value(
  618. self.application.settings["cookie_secret"],
  619. name,
  620. value,
  621. max_age_days=max_age_days,
  622. min_version=min_version,
  623. )
  624. def get_secure_cookie_key_version(
  625. self, name: str, value: str = None
  626. ) -> Optional[int]:
  627. """Returns the signing key version of the secure cookie.
  628. The version is returned as int.
  629. """
  630. self.require_setting("cookie_secret", "secure cookies")
  631. if value is None:
  632. value = self.get_cookie(name)
  633. if value is None:
  634. return None
  635. return get_signature_key_version(value)
  636. def redirect(self, url: str, permanent: bool = False, status: int = None) -> None:
  637. """Sends a redirect to the given (optionally relative) URL.
  638. If the ``status`` argument is specified, that value is used as the
  639. HTTP status code; otherwise either 301 (permanent) or 302
  640. (temporary) is chosen based on the ``permanent`` argument.
  641. The default is 302 (temporary).
  642. """
  643. if self._headers_written:
  644. raise Exception("Cannot redirect after headers have been written")
  645. if status is None:
  646. status = 301 if permanent else 302
  647. else:
  648. assert isinstance(status, int) and 300 <= status <= 399
  649. self.set_status(status)
  650. self.set_header("Location", utf8(url))
  651. self.finish()
  652. def write(self, chunk: Union[str, bytes, dict]) -> None:
  653. """Writes the given chunk to the output buffer.
  654. To write the output to the network, use the `flush()` method below.
  655. If the given chunk is a dictionary, we write it as JSON and set
  656. the Content-Type of the response to be ``application/json``.
  657. (if you want to send JSON as a different ``Content-Type``, call
  658. ``set_header`` *after* calling ``write()``).
  659. Note that lists are not converted to JSON because of a potential
  660. cross-site security vulnerability. All JSON output should be
  661. wrapped in a dictionary. More details at
  662. http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ and
  663. https://github.com/facebook/tornado/issues/1009
  664. """
  665. if self._finished:
  666. raise RuntimeError("Cannot write() after finish()")
  667. if not isinstance(chunk, (bytes, unicode_type, dict)):
  668. message = "write() only accepts bytes, unicode, and dict objects"
  669. if isinstance(chunk, list):
  670. message += (
  671. ". Lists not accepted for security reasons; see "
  672. + "http://www.tornadoweb.org/en/stable/web.html#tornado.web.RequestHandler.write" # noqa: E501
  673. )
  674. raise TypeError(message)
  675. if isinstance(chunk, dict):
  676. chunk = escape.json_encode(chunk)
  677. self.set_header("Content-Type", "application/json; charset=UTF-8")
  678. chunk = utf8(chunk)
  679. self._write_buffer.append(chunk)
  680. def render(self, template_name: str, **kwargs: Any) -> "Future[None]":
  681. """Renders the template with the given arguments as the response.
  682. ``render()`` calls ``finish()``, so no other output methods can be called
  683. after it.
  684. Returns a `.Future` with the same semantics as the one returned by `finish`.
  685. Awaiting this `.Future` is optional.
  686. .. versionchanged:: 5.1
  687. Now returns a `.Future` instead of ``None``.
  688. """
  689. if self._finished:
  690. raise RuntimeError("Cannot render() after finish()")
  691. html = self.render_string(template_name, **kwargs)
  692. # Insert the additional JS and CSS added by the modules on the page
  693. js_embed = []
  694. js_files = []
  695. css_embed = []
  696. css_files = []
  697. html_heads = []
  698. html_bodies = []
  699. for module in getattr(self, "_active_modules", {}).values():
  700. embed_part = module.embedded_javascript()
  701. if embed_part:
  702. js_embed.append(utf8(embed_part))
  703. file_part = module.javascript_files()
  704. if file_part:
  705. if isinstance(file_part, (unicode_type, bytes)):
  706. js_files.append(_unicode(file_part))
  707. else:
  708. js_files.extend(file_part)
  709. embed_part = module.embedded_css()
  710. if embed_part:
  711. css_embed.append(utf8(embed_part))
  712. file_part = module.css_files()
  713. if file_part:
  714. if isinstance(file_part, (unicode_type, bytes)):
  715. css_files.append(_unicode(file_part))
  716. else:
  717. css_files.extend(file_part)
  718. head_part = module.html_head()
  719. if head_part:
  720. html_heads.append(utf8(head_part))
  721. body_part = module.html_body()
  722. if body_part:
  723. html_bodies.append(utf8(body_part))
  724. if js_files:
  725. # Maintain order of JavaScript files given by modules
  726. js = self.render_linked_js(js_files)
  727. sloc = html.rindex(b"</body>")
  728. html = html[:sloc] + utf8(js) + b"\n" + html[sloc:]
  729. if js_embed:
  730. js_bytes = self.render_embed_js(js_embed)
  731. sloc = html.rindex(b"</body>")
  732. html = html[:sloc] + js_bytes + b"\n" + html[sloc:]
  733. if css_files:
  734. css = self.render_linked_css(css_files)
  735. hloc = html.index(b"</head>")
  736. html = html[:hloc] + utf8(css) + b"\n" + html[hloc:]
  737. if css_embed:
  738. css_bytes = self.render_embed_css(css_embed)
  739. hloc = html.index(b"</head>")
  740. html = html[:hloc] + css_bytes + b"\n" + html[hloc:]
  741. if html_heads:
  742. hloc = html.index(b"</head>")
  743. html = html[:hloc] + b"".join(html_heads) + b"\n" + html[hloc:]
  744. if html_bodies:
  745. hloc = html.index(b"</body>")
  746. html = html[:hloc] + b"".join(html_bodies) + b"\n" + html[hloc:]
  747. return self.finish(html)
  748. def render_linked_js(self, js_files: Iterable[str]) -> str:
  749. """Default method used to render the final js links for the
  750. rendered webpage.
  751. Override this method in a sub-classed controller to change the output.
  752. """
  753. paths = []
  754. unique_paths = set() # type: Set[str]
  755. for path in js_files:
  756. if not is_absolute(path):
  757. path = self.static_url(path)
  758. if path not in unique_paths:
  759. paths.append(path)
  760. unique_paths.add(path)
  761. return "".join(
  762. '<script src="'
  763. + escape.xhtml_escape(p)
  764. + '" type="text/javascript"></script>'
  765. for p in paths
  766. )
  767. def render_embed_js(self, js_embed: Iterable[bytes]) -> bytes:
  768. """Default method used to render the final embedded js for the
  769. rendered webpage.
  770. Override this method in a sub-classed controller to change the output.
  771. """
  772. return (
  773. b'<script type="text/javascript">\n//<![CDATA[\n'
  774. + b"\n".join(js_embed)
  775. + b"\n//]]>\n</script>"
  776. )
  777. def render_linked_css(self, css_files: Iterable[str]) -> str:
  778. """Default method used to render the final css links for the
  779. rendered webpage.
  780. Override this method in a sub-classed controller to change the output.
  781. """
  782. paths = []
  783. unique_paths = set() # type: Set[str]
  784. for path in css_files:
  785. if not is_absolute(path):
  786. path = self.static_url(path)
  787. if path not in unique_paths:
  788. paths.append(path)
  789. unique_paths.add(path)
  790. return "".join(
  791. '<link href="' + escape.xhtml_escape(p) + '" '
  792. 'type="text/css" rel="stylesheet"/>'
  793. for p in paths
  794. )
  795. def render_embed_css(self, css_embed: Iterable[bytes]) -> bytes:
  796. """Default method used to render the final embedded css for the
  797. rendered webpage.
  798. Override this method in a sub-classed controller to change the output.
  799. """
  800. return b'<style type="text/css">\n' + b"\n".join(css_embed) + b"\n</style>"
  801. def render_string(self, template_name: str, **kwargs: Any) -> bytes:
  802. """Generate the given template with the given arguments.
  803. We return the generated byte string (in utf8). To generate and
  804. write a template as a response, use render() above.
  805. """
  806. # If no template_path is specified, use the path of the calling file
  807. template_path = self.get_template_path()
  808. if not template_path:
  809. frame = sys._getframe(0)
  810. web_file = frame.f_code.co_filename
  811. while frame.f_code.co_filename == web_file:
  812. frame = frame.f_back
  813. assert frame.f_code.co_filename is not None
  814. template_path = os.path.dirname(frame.f_code.co_filename)
  815. with RequestHandler._template_loader_lock:
  816. if template_path not in RequestHandler._template_loaders:
  817. loader = self.create_template_loader(template_path)
  818. RequestHandler._template_loaders[template_path] = loader
  819. else:
  820. loader = RequestHandler._template_loaders[template_path]
  821. t = loader.load(template_name)
  822. namespace = self.get_template_namespace()
  823. namespace.update(kwargs)
  824. return t.generate(**namespace)
  825. def get_template_namespace(self) -> Dict[str, Any]:
  826. """Returns a dictionary to be used as the default template namespace.
  827. May be overridden by subclasses to add or modify values.
  828. The results of this method will be combined with additional
  829. defaults in the `tornado.template` module and keyword arguments
  830. to `render` or `render_string`.
  831. """
  832. namespace = dict(
  833. handler=self,
  834. request=self.request,
  835. current_user=self.current_user,
  836. locale=self.locale,
  837. _=self.locale.translate,
  838. pgettext=self.locale.pgettext,
  839. static_url=self.static_url,
  840. xsrf_form_html=self.xsrf_form_html,
  841. reverse_url=self.reverse_url,
  842. )
  843. namespace.update(self.ui)
  844. return namespace
  845. def create_template_loader(self, template_path: str) -> template.BaseLoader:
  846. """Returns a new template loader for the given path.
  847. May be overridden by subclasses. By default returns a
  848. directory-based loader on the given path, using the
  849. ``autoescape`` and ``template_whitespace`` application
  850. settings. If a ``template_loader`` application setting is
  851. supplied, uses that instead.
  852. """
  853. settings = self.application.settings
  854. if "template_loader" in settings:
  855. return settings["template_loader"]
  856. kwargs = {}
  857. if "autoescape" in settings:
  858. # autoescape=None means "no escaping", so we have to be sure
  859. # to only pass this kwarg if the user asked for it.
  860. kwargs["autoescape"] = settings["autoescape"]
  861. if "template_whitespace" in settings:
  862. kwargs["whitespace"] = settings["template_whitespace"]
  863. return template.Loader(template_path, **kwargs)
  864. def flush(self, include_footers: bool = False) -> "Future[None]":
  865. """Flushes the current output buffer to the network.
  866. The ``callback`` argument, if given, can be used for flow control:
  867. it will be run when all flushed data has been written to the socket.
  868. Note that only one flush callback can be outstanding at a time;
  869. if another flush occurs before the previous flush's callback
  870. has been run, the previous callback will be discarded.
  871. .. versionchanged:: 4.0
  872. Now returns a `.Future` if no callback is given.
  873. .. versionchanged:: 6.0
  874. The ``callback`` argument was removed.
  875. """
  876. assert self.request.connection is not None
  877. chunk = b"".join(self._write_buffer)
  878. self._write_buffer = []
  879. if not self._headers_written:
  880. self._headers_written = True
  881. for transform in self._transforms:
  882. assert chunk is not None
  883. (
  884. self._status_code,
  885. self._headers,
  886. chunk,
  887. ) = transform.transform_first_chunk(
  888. self._status_code, self._headers, chunk, include_footers
  889. )
  890. # Ignore the chunk and only write the headers for HEAD requests
  891. if self.request.method == "HEAD":
  892. chunk = b""
  893. # Finalize the cookie headers (which have been stored in a side
  894. # object so an outgoing cookie could be overwritten before it
  895. # is sent).
  896. if hasattr(self, "_new_cookie"):
  897. for cookie in self._new_cookie.values():
  898. self.add_header("Set-Cookie", cookie.OutputString(None))
  899. start_line = httputil.ResponseStartLine("", self._status_code, self._reason)
  900. return self.request.connection.write_headers(
  901. start_line, self._headers, chunk
  902. )
  903. else:
  904. for transform in self._transforms:
  905. chunk = transform.transform_chunk(chunk, include_footers)
  906. # Ignore the chunk and only write the headers for HEAD requests
  907. if self.request.method != "HEAD":
  908. return self.request.connection.write(chunk)
  909. else:
  910. future = Future() # type: Future[None]
  911. future.set_result(None)
  912. return future
  913. def finish(self, chunk: Union[str, bytes, dict] = None) -> "Future[None]":
  914. """Finishes this response, ending the HTTP request.
  915. Passing a ``chunk`` to ``finish()`` is equivalent to passing that
  916. chunk to ``write()`` and then calling ``finish()`` with no arguments.
  917. Returns a `.Future` which may optionally be awaited to track the sending
  918. of the response to the client. This `.Future` resolves when all the response
  919. data has been sent, and raises an error if the connection is closed before all
  920. data can be sent.
  921. .. versionchanged:: 5.1
  922. Now returns a `.Future` instead of ``None``.
  923. """
  924. if self._finished:
  925. raise RuntimeError("finish() called twice")
  926. if chunk is not None:
  927. self.write(chunk)
  928. # Automatically support ETags and add the Content-Length header if
  929. # we have not flushed any content yet.
  930. if not self._headers_written:
  931. if (
  932. self._status_code == 200
  933. and self.request.method in ("GET", "HEAD")
  934. and "Etag" not in self._headers
  935. ):
  936. self.set_etag_header()
  937. if self.check_etag_header():
  938. self._write_buffer = []
  939. self.set_status(304)
  940. if self._status_code in (204, 304) or (
  941. self._status_code >= 100 and self._status_code < 200
  942. ):
  943. assert not self._write_buffer, (
  944. "Cannot send body with %s" % self._status_code
  945. )
  946. self._clear_headers_for_304()
  947. elif "Content-Length" not in self._headers:
  948. content_length = sum(len(part) for part in self._write_buffer)
  949. self.set_header("Content-Length", content_length)
  950. assert self.request.connection is not None
  951. # Now that the request is finished, clear the callback we
  952. # set on the HTTPConnection (which would otherwise prevent the
  953. # garbage collection of the RequestHandler when there
  954. # are keepalive connections)
  955. self.request.connection.set_close_callback(None) # type: ignore
  956. future = self.flush(include_footers=True)
  957. self.request.connection.finish()
  958. self._log()
  959. self._finished = True
  960. self.on_finish()
  961. self._break_cycles()
  962. return future
  963. def detach(self) -> iostream.IOStream:
  964. """Take control of the underlying stream.
  965. Returns the underlying `.IOStream` object and stops all
  966. further HTTP processing. Intended for implementing protocols
  967. like websockets that tunnel over an HTTP handshake.
  968. This method is only supported when HTTP/1.1 is used.
  969. .. versionadded:: 5.1
  970. """
  971. self._finished = True
  972. # TODO: add detach to HTTPConnection?
  973. return self.request.connection.detach() # type: ignore
  974. def _break_cycles(self) -> None:
  975. # Break up a reference cycle between this handler and the
  976. # _ui_module closures to allow for faster GC on CPython.
  977. self.ui = None # type: ignore
  978. def send_error(self, status_code: int = 500, **kwargs: Any) -> None:
  979. """Sends the given HTTP error code to the browser.
  980. If `flush()` has already been called, it is not possible to send
  981. an error, so this method will simply terminate the response.
  982. If output has been written but not yet flushed, it will be discarded
  983. and replaced with the error page.
  984. Override `write_error()` to customize the error page that is returned.
  985. Additional keyword arguments are passed through to `write_error`.
  986. """
  987. if self._headers_written:
  988. gen_log.error("Cannot send error response after headers written")
  989. if not self._finished:
  990. # If we get an error between writing headers and finishing,
  991. # we are unlikely to be able to finish due to a
  992. # Content-Length mismatch. Try anyway to release the
  993. # socket.
  994. try:
  995. self.finish()
  996. except Exception:
  997. gen_log.error("Failed to flush partial response", exc_info=True)
  998. return
  999. self.clear()
  1000. reason = kwargs.get("reason")
  1001. if "exc_info" in kwargs:
  1002. exception = kwargs["exc_info"][1]
  1003. if isinstance(exception, HTTPError) and exception.reason:
  1004. reason = exception.reason
  1005. self.set_status(status_code, reason=reason)
  1006. try:
  1007. self.write_error(status_code, **kwargs)
  1008. except Exception:
  1009. app_log.error("Uncaught exception in write_error", exc_info=True)
  1010. if not self._finished:
  1011. self.finish()
  1012. def write_error(self, status_code: int, **kwargs: Any) -> None:
  1013. """Override to implement custom error pages.
  1014. ``write_error`` may call `write`, `render`, `set_header`, etc
  1015. to produce output as usual.
  1016. If this error was caused by an uncaught exception (including
  1017. HTTPError), an ``exc_info`` triple will be available as
  1018. ``kwargs["exc_info"]``. Note that this exception may not be
  1019. the "current" exception for purposes of methods like
  1020. ``sys.exc_info()`` or ``traceback.format_exc``.
  1021. """
  1022. if self.settings.get("serve_traceback") and "exc_info" in kwargs:
  1023. # in debug mode, try to send a traceback
  1024. self.set_header("Content-Type", "text/plain")
  1025. for line in traceback.format_exception(*kwargs["exc_info"]):
  1026. self.write(line)
  1027. self.finish()
  1028. else:
  1029. self.finish(
  1030. "<html><title>%(code)d: %(message)s</title>"
  1031. "<body>%(code)d: %(message)s</body></html>"
  1032. % {"code": status_code, "message": self._reason}
  1033. )
  1034. @property
  1035. def locale(self) -> tornado.locale.Locale:
  1036. """The locale for the current session.
  1037. Determined by either `get_user_locale`, which you can override to
  1038. set the locale based on, e.g., a user preference stored in a
  1039. database, or `get_browser_locale`, which uses the ``Accept-Language``
  1040. header.
  1041. .. versionchanged: 4.1
  1042. Added a property setter.
  1043. """
  1044. if not hasattr(self, "_locale"):
  1045. loc = self.get_user_locale()
  1046. if loc is not None:
  1047. self._locale = loc
  1048. else:
  1049. self._locale = self.get_browser_locale()
  1050. assert self._locale
  1051. return self._locale
  1052. @locale.setter
  1053. def locale(self, value: tornado.locale.Locale) -> None:
  1054. self._locale = value
  1055. def get_user_locale(self) -> Optional[tornado.locale.Locale]:
  1056. """Override to determine the locale from the authenticated user.
  1057. If None is returned, we fall back to `get_browser_locale()`.
  1058. This method should return a `tornado.locale.Locale` object,
  1059. most likely obtained via a call like ``tornado.locale.get("en")``
  1060. """
  1061. return None
  1062. def get_browser_locale(self, default: str = "en_US") -> tornado.locale.Locale:
  1063. """Determines the user's locale from ``Accept-Language`` header.
  1064. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
  1065. """
  1066. if "Accept-Language" in self.request.headers:
  1067. languages = self.request.headers["Accept-Language"].split(",")
  1068. locales = []
  1069. for language in languages:
  1070. parts = language.strip().split(";")
  1071. if len(parts) > 1 and parts[1].startswith("q="):
  1072. try:
  1073. score = float(parts[1][2:])
  1074. except (ValueError, TypeError):
  1075. score = 0.0
  1076. else:
  1077. score = 1.0
  1078. locales.append((parts[0], score))
  1079. if locales:
  1080. locales.sort(key=lambda pair: pair[1], reverse=True)
  1081. codes = [l[0] for l in locales]
  1082. return locale.get(*codes)
  1083. return locale.get(default)
  1084. @property
  1085. def current_user(self) -> Any:
  1086. """The authenticated user for this request.
  1087. This is set in one of two ways:
  1088. * A subclass may override `get_current_user()`, which will be called
  1089. automatically the first time ``self.current_user`` is accessed.
  1090. `get_current_user()` will only be called once per request,
  1091. and is cached for future access::
  1092. def get_current_user(self):
  1093. user_cookie = self.get_secure_cookie("user")
  1094. if user_cookie:
  1095. return json.loads(user_cookie)
  1096. return None
  1097. * It may be set as a normal variable, typically from an overridden
  1098. `prepare()`::
  1099. @gen.coroutine
  1100. def prepare(self):
  1101. user_id_cookie = self.get_secure_cookie("user_id")
  1102. if user_id_cookie:
  1103. self.current_user = yield load_user(user_id_cookie)
  1104. Note that `prepare()` may be a coroutine while `get_current_user()`
  1105. may not, so the latter form is necessary if loading the user requires
  1106. asynchronous operations.
  1107. The user object may be any type of the application's choosing.
  1108. """
  1109. if not hasattr(self, "_current_user"):
  1110. self._current_user = self.get_current_user()
  1111. return self._current_user
  1112. @current_user.setter
  1113. def current_user(self, value: Any) -> None:
  1114. self._current_user = value
  1115. def get_current_user(self) -> Any:
  1116. """Override to determine the current user from, e.g., a cookie.
  1117. This method may not be a coroutine.
  1118. """
  1119. return None
  1120. def get_login_url(self) -> str:
  1121. """Override to customize the login URL based on the request.
  1122. By default, we use the ``login_url`` application setting.
  1123. """
  1124. self.require_setting("login_url", "@tornado.web.authenticated")
  1125. return self.application.settings["login_url"]
  1126. def get_template_path(self) -> Optional[str]:
  1127. """Override to customize template path for each handler.
  1128. By default, we use the ``template_path`` application setting.
  1129. Return None to load templates relative to the calling file.
  1130. """
  1131. return self.application.settings.get("template_path")
  1132. @property
  1133. def xsrf_token(self) -> bytes:
  1134. """The XSRF-prevention token for the current user/session.
  1135. To prevent cross-site request forgery, we set an '_xsrf' cookie
  1136. and include the same '_xsrf' value as an argument with all POST
  1137. requests. If the two do not match, we reject the form submission
  1138. as a potential forgery.
  1139. See http://en.wikipedia.org/wiki/Cross-site_request_forgery
  1140. This property is of type `bytes`, but it contains only ASCII
  1141. characters. If a character string is required, there is no
  1142. need to base64-encode it; just decode the byte string as
  1143. UTF-8.
  1144. .. versionchanged:: 3.2.2
  1145. The xsrf token will now be have a random mask applied in every
  1146. request, which makes it safe to include the token in pages
  1147. that are compressed. See http://breachattack.com for more
  1148. information on the issue fixed by this change. Old (version 1)
  1149. cookies will be converted to version 2 when this method is called
  1150. unless the ``xsrf_cookie_version`` `Application` setting is
  1151. set to 1.
  1152. .. versionchanged:: 4.3
  1153. The ``xsrf_cookie_kwargs`` `Application` setting may be
  1154. used to supply additional cookie options (which will be
  1155. passed directly to `set_cookie`). For example,
  1156. ``xsrf_cookie_kwargs=dict(httponly=True, secure=True)``
  1157. will set the ``secure`` and ``httponly`` flags on the
  1158. ``_xsrf`` cookie.
  1159. """
  1160. if not hasattr(self, "_xsrf_token"):
  1161. version, token, timestamp = self._get_raw_xsrf_token()
  1162. output_version = self.settings.get("xsrf_cookie_version", 2)
  1163. cookie_kwargs = self.settings.get("xsrf_cookie_kwargs", {})
  1164. if output_version == 1:
  1165. self._xsrf_token = binascii.b2a_hex(token)
  1166. elif output_version == 2:
  1167. mask = os.urandom(4)
  1168. self._xsrf_token = b"|".join(
  1169. [
  1170. b"2",
  1171. binascii.b2a_hex(mask),
  1172. binascii.b2a_hex(_websocket_mask(mask, token)),
  1173. utf8(str(int(timestamp))),
  1174. ]
  1175. )
  1176. else:
  1177. raise ValueError("unknown xsrf cookie version %d", output_version)
  1178. if version is None:
  1179. if self.current_user and "expires_days" not in cookie_kwargs:
  1180. cookie_kwargs["expires_days"] = 30
  1181. self.set_cookie("_xsrf", self._xsrf_token, **cookie_kwargs)
  1182. return self._xsrf_token
  1183. def _get_raw_xsrf_token(self) -> Tuple[Optional[int], bytes, float]:
  1184. """Read or generate the xsrf token in its raw form.
  1185. The raw_xsrf_token is a tuple containing:
  1186. * version: the version of the cookie from which this token was read,
  1187. or None if we generated a new token in this request.
  1188. * token: the raw token data; random (non-ascii) bytes.
  1189. * timestamp: the time this token was generated (will not be accurate
  1190. for version 1 cookies)
  1191. """
  1192. if not hasattr(self, "_raw_xsrf_token"):
  1193. cookie = self.get_cookie("_xsrf")
  1194. if cookie:
  1195. version, token, timestamp = self._decode_xsrf_token(cookie)
  1196. else:
  1197. version, token, timestamp = None, None, None
  1198. if token is None:
  1199. version = None
  1200. token = os.urandom(16)
  1201. timestamp = time.time()
  1202. assert token is not None
  1203. assert timestamp is not None
  1204. self._raw_xsrf_token = (version, token, timestamp)
  1205. return self._raw_xsrf_token
  1206. def _decode_xsrf_token(
  1207. self, cookie: str
  1208. ) -> Tuple[Optional[int], Optional[bytes], Optional[float]]:
  1209. """Convert a cookie string into a the tuple form returned by
  1210. _get_raw_xsrf_token.
  1211. """
  1212. try:
  1213. m = _signed_value_version_re.match(utf8(cookie))
  1214. if m:
  1215. version = int(m.group(1))
  1216. if version == 2:
  1217. _, mask_str, masked_token, timestamp_str = cookie.split("|")
  1218. mask = binascii.a2b_hex(utf8(mask_str))
  1219. token = _websocket_mask(mask, binascii.a2b_hex(utf8(masked_token)))
  1220. timestamp = int(timestamp_str)
  1221. return version, token, timestamp
  1222. else:
  1223. # Treat unknown versions as not present instead of failing.
  1224. raise Exception("Unknown xsrf cookie version")
  1225. else:
  1226. version = 1
  1227. try:
  1228. token = binascii.a2b_hex(utf8(cookie))
  1229. except (binascii.Error, TypeError):
  1230. token = utf8(cookie)
  1231. # We don't have a usable timestamp in older versions.
  1232. timestamp = int(time.time())
  1233. return (version, token, timestamp)
  1234. except Exception:
  1235. # Catch exceptions and return nothing instead of failing.
  1236. gen_log.debug("Uncaught exception in _decode_xsrf_token", exc_info=True)
  1237. return None, None, None
  1238. def check_xsrf_cookie(self) -> None:
  1239. """Verifies that the ``_xsrf`` cookie matches the ``_xsrf`` argument.
  1240. To prevent cross-site request forgery, we set an ``_xsrf``
  1241. cookie and include the same value as a non-cookie
  1242. field with all ``POST`` requests. If the two do not match, we
  1243. reject the form submission as a potential forgery.
  1244. The ``_xsrf`` value may be set as either a form field named ``_xsrf``
  1245. or in a custom HTTP header named ``X-XSRFToken`` or ``X-CSRFToken``
  1246. (the latter is accepted for compatibility with Django).
  1247. See http://en.wikipedia.org/wiki/Cross-site_request_forgery
  1248. .. versionchanged:: 3.2.2
  1249. Added support for cookie version 2. Both versions 1 and 2 are
  1250. supported.
  1251. """
  1252. # Prior to release 1.1.1, this check was ignored if the HTTP header
  1253. # ``X-Requested-With: XMLHTTPRequest`` was present. This exception
  1254. # has been shown to be insecure and has been removed. For more
  1255. # information please see
  1256. # http://www.djangoproject.com/weblog/2011/feb/08/security/
  1257. # http://weblog.rubyonrails.org/2011/2/8/csrf-protection-bypass-in-ruby-on-rails
  1258. token = (
  1259. self.get_argument("_xsrf", None)
  1260. or self.request.headers.get("X-Xsrftoken")
  1261. or self.request.headers.get("X-Csrftoken")
  1262. )
  1263. if not token:
  1264. raise HTTPError(403, "'_xsrf' argument missing from POST")
  1265. _, token, _ = self._decode_xsrf_token(token)
  1266. _, expected_token, _ = self._get_raw_xsrf_token()
  1267. if not token:
  1268. raise HTTPError(403, "'_xsrf' argument has invalid format")
  1269. if not hmac.compare_digest(utf8(token), utf8(expected_token)):
  1270. raise HTTPError(403, "XSRF cookie does not match POST argument")
  1271. def xsrf_form_html(self) -> str:
  1272. """An HTML ``<input/>`` element to be included with all POST forms.
  1273. It defines the ``_xsrf`` input value, which we check on all POST
  1274. requests to prevent cross-site request forgery. If you have set
  1275. the ``xsrf_cookies`` application setting, you must include this
  1276. HTML within all of your HTML forms.
  1277. In a template, this method should be called with ``{% module
  1278. xsrf_form_html() %}``
  1279. See `check_xsrf_cookie()` above for more information.
  1280. """
  1281. return (
  1282. '<input type="hidden" name="_xsrf" value="'
  1283. + escape.xhtml_escape(self.xsrf_token)
  1284. + '"/>'
  1285. )
  1286. def static_url(self, path: str, include_host: bool = None, **kwargs: Any) -> str:
  1287. """Returns a static URL for the given relative static file path.
  1288. This method requires you set the ``static_path`` setting in your
  1289. application (which specifies the root directory of your static
  1290. files).
  1291. This method returns a versioned url (by default appending
  1292. ``?v=<signature>``), which allows the static files to be
  1293. cached indefinitely. This can be disabled by passing
  1294. ``include_version=False`` (in the default implementation;
  1295. other static file implementations are not required to support
  1296. this, but they may support other options).
  1297. By default this method returns URLs relative to the current
  1298. host, but if ``include_host`` is true the URL returned will be
  1299. absolute. If this handler has an ``include_host`` attribute,
  1300. that value will be used as the default for all `static_url`
  1301. calls that do not pass ``include_host`` as a keyword argument.
  1302. """
  1303. self.require_setting("static_path", "static_url")
  1304. get_url = self.settings.get(
  1305. "static_handler_class", StaticFileHandler
  1306. ).make_static_url
  1307. if include_host is None:
  1308. include_host = getattr(self, "include_host", False)
  1309. if include_host:
  1310. base = self.request.protocol + "://" + self.request.host
  1311. else:
  1312. base = ""
  1313. return base + get_url(self.settings, path, **kwargs)
  1314. def require_setting(self, name: str, feature: str = "this feature") -> None:
  1315. """Raises an exception if the given app setting is not defined."""
  1316. if not self.application.settings.get(name):
  1317. raise Exception(
  1318. "You must define the '%s' setting in your "
  1319. "application to use %s" % (name, feature)
  1320. )
  1321. def reverse_url(self, name: str, *args: Any) -> str:
  1322. """Alias for `Application.reverse_url`."""
  1323. return self.application.reverse_url(name, *args)
  1324. def compute_etag(self) -> Optional[str]:
  1325. """Computes the etag header to be used for this request.
  1326. By default uses a hash of the content written so far.
  1327. May be overridden to provide custom etag implementations,
  1328. or may return None to disable tornado's default etag support.
  1329. """
  1330. hasher = hashlib.sha1()
  1331. for part in self._write_buffer:
  1332. hasher.update(part)
  1333. return '"%s"' % hasher.hexdigest()
  1334. def set_etag_header(self) -> None:
  1335. """Sets the response's Etag header using ``self.compute_etag()``.
  1336. Note: no header will be set if ``compute_etag()`` returns ``None``.
  1337. This method is called automatically when the request is finished.
  1338. """
  1339. etag = self.compute_etag()
  1340. if etag is not None:
  1341. self.set_header("Etag", etag)
  1342. def check_etag_header(self) -> bool:
  1343. """Checks the ``Etag`` header against requests's ``If-None-Match``.
  1344. Returns ``True`` if the request's Etag matches and a 304 should be
  1345. returned. For example::
  1346. self.set_etag_header()
  1347. if self.check_etag_header():
  1348. self.set_status(304)
  1349. return
  1350. This method is called automatically when the request is finished,
  1351. but may be called earlier for applications that override
  1352. `compute_etag` and want to do an early check for ``If-None-Match``
  1353. before completing the request. The ``Etag`` header should be set
  1354. (perhaps with `set_etag_header`) before calling this method.
  1355. """
  1356. computed_etag = utf8(self._headers.get("Etag", ""))
  1357. # Find all weak and strong etag values from If-None-Match header
  1358. # because RFC 7232 allows multiple etag values in a single header.
  1359. etags = re.findall(
  1360. br'\*|(?:W/)?"[^"]*"', utf8(self.request.headers.get("If-None-Match", ""))
  1361. )
  1362. if not computed_etag or not etags:
  1363. return False
  1364. match = False
  1365. if etags[0] == b"*":
  1366. match = True
  1367. else:
  1368. # Use a weak comparison when comparing entity-tags.
  1369. def val(x: bytes) -> bytes:
  1370. return x[2:] if x.startswith(b"W/") else x
  1371. for etag in etags:
  1372. if val(etag) == val(computed_etag):
  1373. match = True
  1374. break
  1375. return match
  1376. async def _execute(
  1377. self, transforms: List["OutputTransform"], *args: bytes, **kwargs: bytes
  1378. ) -> None:
  1379. """Executes this request with the given output transforms."""
  1380. self._transforms = transforms
  1381. try:
  1382. if self.request.method not in self.SUPPORTED_METHODS:
  1383. raise HTTPError(405)
  1384. self.path_args = [self.decode_argument(arg) for arg in args]
  1385. self.path_kwargs = dict(
  1386. (k, self.decode_argument(v, name=k)) for (k, v) in kwargs.items()
  1387. )
  1388. # If XSRF cookies are turned on, reject form submissions without
  1389. # the proper cookie
  1390. if self.request.method not in (
  1391. "GET",
  1392. "HEAD",
  1393. "OPTIONS",
  1394. ) and self.application.settings.get("xsrf_cookies"):
  1395. self.check_xsrf_cookie()
  1396. result = self.prepare()
  1397. if result is not None:
  1398. result = await result
  1399. if self._prepared_future is not None:
  1400. # Tell the Application we've finished with prepare()
  1401. # and are ready for the body to arrive.
  1402. future_set_result_unless_cancelled(self._prepared_future, None)
  1403. if self._finished:
  1404. return
  1405. if _has_stream_request_body(self.__class__):
  1406. # In streaming mode request.body is a Future that signals
  1407. # the body has been completely received. The Future has no
  1408. # result; the data has been passed to self.data_received
  1409. # instead.
  1410. try:
  1411. await self.request._body_future
  1412. except iostream.StreamClosedError:
  1413. return
  1414. method = getattr(self, self.request.method.lower())
  1415. result = method(*self.path_args, **self.path_kwargs)
  1416. if result is not None:
  1417. result = await result
  1418. if self._auto_finish and not self._finished:
  1419. self.finish()
  1420. except Exception as e:
  1421. try:
  1422. self._handle_request_exception(e)
  1423. except Exception:
  1424. app_log.error("Exception in exception handler", exc_info=True)
  1425. finally:
  1426. # Unset result to avoid circular references
  1427. result = None
  1428. if self._prepared_future is not None and not self._prepared_future.done():
  1429. # In case we failed before setting _prepared_future, do it
  1430. # now (to unblock the HTTP server). Note that this is not
  1431. # in a finally block to avoid GC issues prior to Python 3.4.
  1432. self._prepared_future.set_result(None)
  1433. def data_received(self, chunk: bytes) -> Optional[Awaitable[None]]:
  1434. """Implement this method to handle streamed request data.
  1435. Requires the `.stream_request_body` decorator.
  1436. May be a coroutine for flow control.
  1437. """
  1438. raise NotImplementedError()
  1439. def _log(self) -> None:
  1440. """Logs the current request.
  1441. Sort of deprecated since this functionality was moved to the
  1442. Application, but left in place for the benefit of existing apps
  1443. that have overridden this method.
  1444. """
  1445. self.application.log_request(self)
  1446. def _request_summary(self) -> str:
  1447. return "%s %s (%s)" % (
  1448. self.request.method,
  1449. self.request.uri,
  1450. self.request.remote_ip,
  1451. )
  1452. def _handle_request_exception(self, e: BaseException) -> None:
  1453. if isinstance(e, Finish):
  1454. # Not an error; just finish the request without logging.
  1455. if not self._finished:
  1456. self.finish(*e.args)
  1457. return
  1458. try:
  1459. self.log_exception(*sys.exc_info())
  1460. except Exception:
  1461. # An error here should still get a best-effort send_error()
  1462. # to avoid leaking the connection.
  1463. app_log.error("Error in exception logger", exc_info=True)
  1464. if self._finished:
  1465. # Extra errors after the request has been finished should
  1466. # be logged, but there is no reason to continue to try and
  1467. # send a response.
  1468. return
  1469. if isinstance(e, HTTPError):
  1470. self.send_error(e.status_code, exc_info=sys.exc_info())
  1471. else:
  1472. self.send_error(500, exc_info=sys.exc_info())
  1473. def log_exception(
  1474. self,
  1475. typ: "Optional[Type[BaseException]]",
  1476. value: Optional[BaseException],
  1477. tb: Optional[TracebackType],
  1478. ) -> None:
  1479. """Override to customize logging of uncaught exceptions.
  1480. By default logs instances of `HTTPError` as warnings without
  1481. stack traces (on the ``tornado.general`` logger), and all
  1482. other exceptions as errors with stack traces (on the
  1483. ``tornado.application`` logger).
  1484. .. versionadded:: 3.1
  1485. """
  1486. if isinstance(value, HTTPError):
  1487. if value.log_message:
  1488. format = "%d %s: " + value.log_message
  1489. args = [value.status_code, self._request_summary()] + list(value.args)
  1490. gen_log.warning(format, *args)
  1491. else:
  1492. app_log.error( # type: ignore
  1493. "Uncaught exception %s\n%r",
  1494. self._request_summary(),
  1495. self.request,
  1496. exc_info=(typ, value, tb),
  1497. )
  1498. def _ui_module(self, name: str, module: Type["UIModule"]) -> Callable[..., str]:
  1499. def render(*args, **kwargs) -> str: # type: ignore
  1500. if not hasattr(self, "_active_modules"):
  1501. self._active_modules = {} # type: Dict[str, UIModule]
  1502. if name not in self._active_modules:
  1503. self._active_modules[name] = module(self)
  1504. rendered = self._active_modules[name].render(*args, **kwargs)
  1505. return rendered
  1506. return render
  1507. def _ui_method(self, method: Callable[..., str]) -> Callable[..., str]:
  1508. return lambda *args, **kwargs: method(self, *args, **kwargs)
  1509. def _clear_headers_for_304(self) -> None:
  1510. # 304 responses should not contain entity headers (defined in
  1511. # http://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html#sec7.1)
  1512. # not explicitly allowed by
  1513. # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5
  1514. headers = [
  1515. "Allow",
  1516. "Content-Encoding",
  1517. "Content-Language",
  1518. "Content-Length",
  1519. "Content-MD5",
  1520. "Content-Range",
  1521. "Content-Type",
  1522. "Last-Modified",
  1523. ]
  1524. for h in headers:
  1525. self.clear_header(h)
  1526. def stream_request_body(cls: Type[RequestHandler]) -> Type[RequestHandler]:
  1527. """Apply to `RequestHandler` subclasses to enable streaming body support.
  1528. This decorator implies the following changes:
  1529. * `.HTTPServerRequest.body` is undefined, and body arguments will not
  1530. be included in `RequestHandler.get_argument`.
  1531. * `RequestHandler.prepare` is called when the request headers have been
  1532. read instead of after the entire body has been read.
  1533. * The subclass must define a method ``data_received(self, data):``, which
  1534. will be called zero or more times as data is available. Note that
  1535. if the request has an empty body, ``data_received`` may not be called.
  1536. * ``prepare`` and ``data_received`` may return Futures (such as via
  1537. ``@gen.coroutine``, in which case the next method will not be called
  1538. until those futures have completed.
  1539. * The regular HTTP method (``post``, ``put``, etc) will be called after
  1540. the entire body has been read.
  1541. See the `file receiver demo <https://github.com/tornadoweb/tornado/tree/master/demos/file_upload/>`_
  1542. for example usage.
  1543. """ # noqa: E501
  1544. if not issubclass(cls, RequestHandler):
  1545. raise TypeError("expected subclass of RequestHandler, got %r", cls)
  1546. cls._stream_request_body = True
  1547. return cls
  1548. def _has_stream_request_body(cls: Type[RequestHandler]) -> bool:
  1549. if not issubclass(cls, RequestHandler):
  1550. raise TypeError("expected subclass of RequestHandler, got %r", cls)
  1551. return cls._stream_request_body
  1552. def removeslash(
  1553. method: Callable[..., Optional[Awaitable[None]]]
  1554. ) -> Callable[..., Optional[Awaitable[None]]]:
  1555. """Use this decorator to remove trailing slashes from the request path.
  1556. For example, a request to ``/foo/`` would redirect to ``/foo`` with this
  1557. decorator. Your request handler mapping should use a regular expression
  1558. like ``r'/foo/*'`` in conjunction with using the decorator.
  1559. """
  1560. @functools.wraps(method)
  1561. def wrapper( # type: ignore
  1562. self: RequestHandler, *args, **kwargs
  1563. ) -> Optional[Awaitable[None]]:
  1564. if self.request.path.endswith("/"):
  1565. if self.request.method in ("GET", "HEAD"):
  1566. uri = self.request.path.rstrip("/")
  1567. if uri: # don't try to redirect '/' to ''
  1568. if self.request.query:
  1569. uri += "?" + self.request.query
  1570. self.redirect(uri, permanent=True)
  1571. return None
  1572. else:
  1573. raise HTTPError(404)
  1574. return method(self, *args, **kwargs)
  1575. return wrapper
  1576. def addslash(
  1577. method: Callable[..., Optional[Awaitable[None]]]
  1578. ) -> Callable[..., Optional[Awaitable[None]]]:
  1579. """Use this decorator to add a missing trailing slash to the request path.
  1580. For example, a request to ``/foo`` would redirect to ``/foo/`` with this
  1581. decorator. Your request handler mapping should use a regular expression
  1582. like ``r'/foo/?'`` in conjunction with using the decorator.
  1583. """
  1584. @functools.wraps(method)
  1585. def wrapper( # type: ignore
  1586. self: RequestHandler, *args, **kwargs
  1587. ) -> Optional[Awaitable[None]]:
  1588. if not self.request.path.endswith("/"):
  1589. if self.request.method in ("GET", "HEAD"):
  1590. uri = self.request.path + "/"
  1591. if self.request.query:
  1592. uri += "?" + self.request.query
  1593. self.redirect(uri, permanent=True)
  1594. return None
  1595. raise HTTPError(404)
  1596. return method(self, *args, **kwargs)
  1597. return wrapper
  1598. class _ApplicationRouter(ReversibleRuleRouter):
  1599. """Routing implementation used internally by `Application`.
  1600. Provides a binding between `Application` and `RequestHandler`.
  1601. This implementation extends `~.routing.ReversibleRuleRouter` in a couple of ways:
  1602. * it allows to use `RequestHandler` subclasses as `~.routing.Rule` target and
  1603. * it allows to use a list/tuple of rules as `~.routing.Rule` target.
  1604. ``process_rule`` implementation will substitute this list with an appropriate
  1605. `_ApplicationRouter` instance.
  1606. """
  1607. def __init__(self, application: "Application", rules: _RuleList = None) -> None:
  1608. assert isinstance(application, Application)
  1609. self.application = application
  1610. super(_ApplicationRouter, self).__init__(rules)
  1611. def process_rule(self, rule: Rule) -> Rule:
  1612. rule = super(_ApplicationRouter, self).process_rule(rule)
  1613. if isinstance(rule.target, (list, tuple)):
  1614. rule.target = _ApplicationRouter( # type: ignore
  1615. self.application, rule.target
  1616. )
  1617. return rule
  1618. def get_target_delegate(
  1619. self, target: Any, request: httputil.HTTPServerRequest, **target_params: Any
  1620. ) -> Optional[httputil.HTTPMessageDelegate]:
  1621. if isclass(target) and issubclass(target, RequestHandler):
  1622. return self.application.get_handler_delegate(
  1623. request, target, **target_params
  1624. )
  1625. return super(_ApplicationRouter, self).get_target_delegate(
  1626. target, request, **target_params
  1627. )
  1628. class Application(ReversibleRouter):
  1629. r"""A collection of request handlers that make up a web application.
  1630. Instances of this class are callable and can be passed directly to
  1631. HTTPServer to serve the application::
  1632. application = web.Application([
  1633. (r"/", MainPageHandler),
  1634. ])
  1635. http_server = httpserver.HTTPServer(application)
  1636. http_server.listen(8080)
  1637. ioloop.IOLoop.current().start()
  1638. The constructor for this class takes in a list of `~.routing.Rule`
  1639. objects or tuples of values corresponding to the arguments of
  1640. `~.routing.Rule` constructor: ``(matcher, target, [target_kwargs], [name])``,
  1641. the values in square brackets being optional. The default matcher is
  1642. `~.routing.PathMatches`, so ``(regexp, target)`` tuples can also be used
  1643. instead of ``(PathMatches(regexp), target)``.
  1644. A common routing target is a `RequestHandler` subclass, but you can also
  1645. use lists of rules as a target, which create a nested routing configuration::
  1646. application = web.Application([
  1647. (HostMatches("example.com"), [
  1648. (r"/", MainPageHandler),
  1649. (r"/feed", FeedHandler),
  1650. ]),
  1651. ])
  1652. In addition to this you can use nested `~.routing.Router` instances,
  1653. `~.httputil.HTTPMessageDelegate` subclasses and callables as routing targets
  1654. (see `~.routing` module docs for more information).
  1655. When we receive requests, we iterate over the list in order and
  1656. instantiate an instance of the first request class whose regexp
  1657. matches the request path. The request class can be specified as
  1658. either a class object or a (fully-qualified) name.
  1659. A dictionary may be passed as the third element (``target_kwargs``)
  1660. of the tuple, which will be used as keyword arguments to the handler's
  1661. constructor and `~RequestHandler.initialize` method. This pattern
  1662. is used for the `StaticFileHandler` in this example (note that a
  1663. `StaticFileHandler` can be installed automatically with the
  1664. static_path setting described below)::
  1665. application = web.Application([
  1666. (r"/static/(.*)", web.StaticFileHandler, {"path": "/var/www"}),
  1667. ])
  1668. We support virtual hosts with the `add_handlers` method, which takes in
  1669. a host regular expression as the first argument::
  1670. application.add_handlers(r"www\.myhost\.com", [
  1671. (r"/article/([0-9]+)", ArticleHandler),
  1672. ])
  1673. If there's no match for the current request's host, then ``default_host``
  1674. parameter value is matched against host regular expressions.
  1675. .. warning::
  1676. Applications that do not use TLS may be vulnerable to :ref:`DNS
  1677. rebinding <dnsrebinding>` attacks. This attack is especially
  1678. relevant to applications that only listen on ``127.0.0.1`` or
  1679. other private networks. Appropriate host patterns must be used
  1680. (instead of the default of ``r'.*'``) to prevent this risk. The
  1681. ``default_host`` argument must not be used in applications that
  1682. may be vulnerable to DNS rebinding.
  1683. You can serve static files by sending the ``static_path`` setting
  1684. as a keyword argument. We will serve those files from the
  1685. ``/static/`` URI (this is configurable with the
  1686. ``static_url_prefix`` setting), and we will serve ``/favicon.ico``
  1687. and ``/robots.txt`` from the same directory. A custom subclass of
  1688. `StaticFileHandler` can be specified with the
  1689. ``static_handler_class`` setting.
  1690. .. versionchanged:: 4.5
  1691. Integration with the new `tornado.routing` module.
  1692. """
  1693. def __init__(
  1694. self,
  1695. handlers: _RuleList = None,
  1696. default_host: str = None,
  1697. transforms: List[Type["OutputTransform"]] = None,
  1698. **settings: Any
  1699. ) -> None:
  1700. if transforms is None:
  1701. self.transforms = [] # type: List[Type[OutputTransform]]
  1702. if settings.get("compress_response") or settings.get("gzip"):
  1703. self.transforms.append(GZipContentEncoding)
  1704. else:
  1705. self.transforms = transforms
  1706. self.default_host = default_host
  1707. self.settings = settings
  1708. self.ui_modules = {
  1709. "linkify": _linkify,
  1710. "xsrf_form_html": _xsrf_form_html,
  1711. "Template": TemplateModule,
  1712. }
  1713. self.ui_methods = {} # type: Dict[str, Callable[..., str]]
  1714. self._load_ui_modules(settings.get("ui_modules", {}))
  1715. self._load_ui_methods(settings.get("ui_methods", {}))
  1716. if self.settings.get("static_path"):
  1717. path = self.settings["static_path"]
  1718. handlers = list(handlers or [])
  1719. static_url_prefix = settings.get("static_url_prefix", "/static/")
  1720. static_handler_class = settings.get(
  1721. "static_handler_class", StaticFileHandler
  1722. )
  1723. static_handler_args = settings.get("static_handler_args", {})
  1724. static_handler_args["path"] = path
  1725. for pattern in [
  1726. re.escape(static_url_prefix) + r"(.*)",
  1727. r"/(favicon\.ico)",
  1728. r"/(robots\.txt)",
  1729. ]:
  1730. handlers.insert(0, (pattern, static_handler_class, static_handler_args))
  1731. if self.settings.get("debug"):
  1732. self.settings.setdefault("autoreload", True)
  1733. self.settings.setdefault("compiled_template_cache", False)
  1734. self.settings.setdefault("static_hash_cache", False)
  1735. self.settings.setdefault("serve_traceback", True)
  1736. self.wildcard_router = _ApplicationRouter(self, handlers)
  1737. self.default_router = _ApplicationRouter(
  1738. self, [Rule(AnyMatches(), self.wildcard_router)]
  1739. )
  1740. # Automatically reload modified modules
  1741. if self.settings.get("autoreload"):
  1742. from tornado import autoreload
  1743. autoreload.start()
  1744. def listen(self, port: int, address: str = "", **kwargs: Any) -> HTTPServer:
  1745. """Starts an HTTP server for this application on the given port.
  1746. This is a convenience alias for creating an `.HTTPServer`
  1747. object and calling its listen method. Keyword arguments not
  1748. supported by `HTTPServer.listen <.TCPServer.listen>` are passed to the
  1749. `.HTTPServer` constructor. For advanced uses
  1750. (e.g. multi-process mode), do not use this method; create an
  1751. `.HTTPServer` and call its
  1752. `.TCPServer.bind`/`.TCPServer.start` methods directly.
  1753. Note that after calling this method you still need to call
  1754. ``IOLoop.current().start()`` to start the server.
  1755. Returns the `.HTTPServer` object.
  1756. .. versionchanged:: 4.3
  1757. Now returns the `.HTTPServer` object.
  1758. """
  1759. server = HTTPServer(self, **kwargs)
  1760. server.listen(port, address)
  1761. return server
  1762. def add_handlers(self, host_pattern: str, host_handlers: _RuleList) -> None:
  1763. """Appends the given handlers to our handler list.
  1764. Host patterns are processed sequentially in the order they were
  1765. added. All matching patterns will be considered.
  1766. """
  1767. host_matcher = HostMatches(host_pattern)
  1768. rule = Rule(host_matcher, _ApplicationRouter(self, host_handlers))
  1769. self.default_router.rules.insert(-1, rule)
  1770. if self.default_host is not None:
  1771. self.wildcard_router.add_rules(
  1772. [(DefaultHostMatches(self, host_matcher.host_pattern), host_handlers)]
  1773. )
  1774. def add_transform(self, transform_class: Type["OutputTransform"]) -> None:
  1775. self.transforms.append(transform_class)
  1776. def _load_ui_methods(self, methods: Any) -> None:
  1777. if isinstance(methods, types.ModuleType):
  1778. self._load_ui_methods(dict((n, getattr(methods, n)) for n in dir(methods)))
  1779. elif isinstance(methods, list):
  1780. for m in methods:
  1781. self._load_ui_methods(m)
  1782. else:
  1783. for name, fn in methods.items():
  1784. if (
  1785. not name.startswith("_")
  1786. and hasattr(fn, "__call__")
  1787. and name[0].lower() == name[0]
  1788. ):
  1789. self.ui_methods[name] = fn
  1790. def _load_ui_modules(self, modules: Any) -> None:
  1791. if isinstance(modules, types.ModuleType):
  1792. self._load_ui_modules(dict((n, getattr(modules, n)) for n in dir(modules)))
  1793. elif isinstance(modules, list):
  1794. for m in modules:
  1795. self._load_ui_modules(m)
  1796. else:
  1797. assert isinstance(modules, dict)
  1798. for name, cls in modules.items():
  1799. try:
  1800. if issubclass(cls, UIModule):
  1801. self.ui_modules[name] = cls
  1802. except TypeError:
  1803. pass
  1804. def __call__(
  1805. self, request: httputil.HTTPServerRequest
  1806. ) -> Optional[Awaitable[None]]:
  1807. # Legacy HTTPServer interface
  1808. dispatcher = self.find_handler(request)
  1809. return dispatcher.execute()
  1810. def find_handler(
  1811. self, request: httputil.HTTPServerRequest, **kwargs: Any
  1812. ) -> "_HandlerDelegate":
  1813. route = self.default_router.find_handler(request)
  1814. if route is not None:
  1815. return cast("_HandlerDelegate", route)
  1816. if self.settings.get("default_handler_class"):
  1817. return self.get_handler_delegate(
  1818. request,
  1819. self.settings["default_handler_class"],
  1820. self.settings.get("default_handler_args", {}),
  1821. )
  1822. return self.get_handler_delegate(request, ErrorHandler, {"status_code": 404})
  1823. def get_handler_delegate(
  1824. self,
  1825. request: httputil.HTTPServerRequest,
  1826. target_class: Type[RequestHandler],
  1827. target_kwargs: Dict[str, Any] = None,
  1828. path_args: List[bytes] = None,
  1829. path_kwargs: Dict[str, bytes] = None,
  1830. ) -> "_HandlerDelegate":
  1831. """Returns `~.httputil.HTTPMessageDelegate` that can serve a request
  1832. for application and `RequestHandler` subclass.
  1833. :arg httputil.HTTPServerRequest request: current HTTP request.
  1834. :arg RequestHandler target_class: a `RequestHandler` class.
  1835. :arg dict target_kwargs: keyword arguments for ``target_class`` constructor.
  1836. :arg list path_args: positional arguments for ``target_class`` HTTP method that
  1837. will be executed while handling a request (``get``, ``post`` or any other).
  1838. :arg dict path_kwargs: keyword arguments for ``target_class`` HTTP method.
  1839. """
  1840. return _HandlerDelegate(
  1841. self, request, target_class, target_kwargs, path_args, path_kwargs
  1842. )
  1843. def reverse_url(self, name: str, *args: Any) -> str:
  1844. """Returns a URL path for handler named ``name``
  1845. The handler must be added to the application as a named `URLSpec`.
  1846. Args will be substituted for capturing groups in the `URLSpec` regex.
  1847. They will be converted to strings if necessary, encoded as utf8,
  1848. and url-escaped.
  1849. """
  1850. reversed_url = self.default_router.reverse_url(name, *args)
  1851. if reversed_url is not None:
  1852. return reversed_url
  1853. raise KeyError("%s not found in named urls" % name)
  1854. def log_request(self, handler: RequestHandler) -> None:
  1855. """Writes a completed HTTP request to the logs.
  1856. By default writes to the python root logger. To change
  1857. this behavior either subclass Application and override this method,
  1858. or pass a function in the application settings dictionary as
  1859. ``log_function``.
  1860. """
  1861. if "log_function" in self.settings:
  1862. self.settings["log_function"](handler)
  1863. return
  1864. if handler.get_status() < 400:
  1865. log_method = access_log.info
  1866. elif handler.get_status() < 500:
  1867. log_method = access_log.warning
  1868. else:
  1869. log_method = access_log.error
  1870. request_time = 1000.0 * handler.request.request_time()
  1871. log_method(
  1872. "%d %s %.2fms",
  1873. handler.get_status(),
  1874. handler._request_summary(),
  1875. request_time,
  1876. )
  1877. class _HandlerDelegate(httputil.HTTPMessageDelegate):
  1878. def __init__(
  1879. self,
  1880. application: Application,
  1881. request: httputil.HTTPServerRequest,
  1882. handler_class: Type[RequestHandler],
  1883. handler_kwargs: Optional[Dict[str, Any]],
  1884. path_args: Optional[List[bytes]],
  1885. path_kwargs: Optional[Dict[str, bytes]],
  1886. ) -> None:
  1887. self.application = application
  1888. self.connection = request.connection
  1889. self.request = request
  1890. self.handler_class = handler_class
  1891. self.handler_kwargs = handler_kwargs or {}
  1892. self.path_args = path_args or []
  1893. self.path_kwargs = path_kwargs or {}
  1894. self.chunks = [] # type: List[bytes]
  1895. self.stream_request_body = _has_stream_request_body(self.handler_class)
  1896. def headers_received(
  1897. self,
  1898. start_line: Union[httputil.RequestStartLine, httputil.ResponseStartLine],
  1899. headers: httputil.HTTPHeaders,
  1900. ) -> Optional[Awaitable[None]]:
  1901. if self.stream_request_body:
  1902. self.request._body_future = Future()
  1903. return self.execute()
  1904. return None
  1905. def data_received(self, data: bytes) -> Optional[Awaitable[None]]:
  1906. if self.stream_request_body:
  1907. return self.handler.data_received(data)
  1908. else:
  1909. self.chunks.append(data)
  1910. return None
  1911. def finish(self) -> None:
  1912. if self.stream_request_body:
  1913. future_set_result_unless_cancelled(self.request._body_future, None)
  1914. else:
  1915. self.request.body = b"".join(self.chunks)
  1916. self.request._parse_body()
  1917. self.execute()
  1918. def on_connection_close(self) -> None:
  1919. if self.stream_request_body:
  1920. self.handler.on_connection_close()
  1921. else:
  1922. self.chunks = None # type: ignore
  1923. def execute(self) -> Optional[Awaitable[None]]:
  1924. # If template cache is disabled (usually in the debug mode),
  1925. # re-compile templates and reload static files on every
  1926. # request so you don't need to restart to see changes
  1927. if not self.application.settings.get("compiled_template_cache", True):
  1928. with RequestHandler._template_loader_lock:
  1929. for loader in RequestHandler._template_loaders.values():
  1930. loader.reset()
  1931. if not self.application.settings.get("static_hash_cache", True):
  1932. StaticFileHandler.reset()
  1933. self.handler = self.handler_class(
  1934. self.application, self.request, **self.handler_kwargs
  1935. )
  1936. transforms = [t(self.request) for t in self.application.transforms]
  1937. if self.stream_request_body:
  1938. self.handler._prepared_future = Future()
  1939. # Note that if an exception escapes handler._execute it will be
  1940. # trapped in the Future it returns (which we are ignoring here,
  1941. # leaving it to be logged when the Future is GC'd).
  1942. # However, that shouldn't happen because _execute has a blanket
  1943. # except handler, and we cannot easily access the IOLoop here to
  1944. # call add_future (because of the requirement to remain compatible
  1945. # with WSGI)
  1946. fut = gen.convert_yielded(
  1947. self.handler._execute(transforms, *self.path_args, **self.path_kwargs)
  1948. )
  1949. fut.add_done_callback(lambda f: f.result())
  1950. # If we are streaming the request body, then execute() is finished
  1951. # when the handler has prepared to receive the body. If not,
  1952. # it doesn't matter when execute() finishes (so we return None)
  1953. return self.handler._prepared_future
  1954. class HTTPError(Exception):
  1955. """An exception that will turn into an HTTP error response.
  1956. Raising an `HTTPError` is a convenient alternative to calling
  1957. `RequestHandler.send_error` since it automatically ends the
  1958. current function.
  1959. To customize the response sent with an `HTTPError`, override
  1960. `RequestHandler.write_error`.
  1961. :arg int status_code: HTTP status code. Must be listed in
  1962. `httplib.responses <http.client.responses>` unless the ``reason``
  1963. keyword argument is given.
  1964. :arg str log_message: Message to be written to the log for this error
  1965. (will not be shown to the user unless the `Application` is in debug
  1966. mode). May contain ``%s``-style placeholders, which will be filled
  1967. in with remaining positional parameters.
  1968. :arg str reason: Keyword-only argument. The HTTP "reason" phrase
  1969. to pass in the status line along with ``status_code``. Normally
  1970. determined automatically from ``status_code``, but can be used
  1971. to use a non-standard numeric code.
  1972. """
  1973. def __init__(
  1974. self, status_code: int = 500, log_message: str = None, *args: Any, **kwargs: Any
  1975. ) -> None:
  1976. self.status_code = status_code
  1977. self.log_message = log_message
  1978. self.args = args
  1979. self.reason = kwargs.get("reason", None)
  1980. if log_message and not args:
  1981. self.log_message = log_message.replace("%", "%%")
  1982. def __str__(self) -> str:
  1983. message = "HTTP %d: %s" % (
  1984. self.status_code,
  1985. self.reason or httputil.responses.get(self.status_code, "Unknown"),
  1986. )
  1987. if self.log_message:
  1988. return message + " (" + (self.log_message % self.args) + ")"
  1989. else:
  1990. return message
  1991. class Finish(Exception):
  1992. """An exception that ends the request without producing an error response.
  1993. When `Finish` is raised in a `RequestHandler`, the request will
  1994. end (calling `RequestHandler.finish` if it hasn't already been
  1995. called), but the error-handling methods (including
  1996. `RequestHandler.write_error`) will not be called.
  1997. If `Finish()` was created with no arguments, the pending response
  1998. will be sent as-is. If `Finish()` was given an argument, that
  1999. argument will be passed to `RequestHandler.finish()`.
  2000. This can be a more convenient way to implement custom error pages
  2001. than overriding ``write_error`` (especially in library code)::
  2002. if self.current_user is None:
  2003. self.set_status(401)
  2004. self.set_header('WWW-Authenticate', 'Basic realm="something"')
  2005. raise Finish()
  2006. .. versionchanged:: 4.3
  2007. Arguments passed to ``Finish()`` will be passed on to
  2008. `RequestHandler.finish`.
  2009. """
  2010. pass
  2011. class MissingArgumentError(HTTPError):
  2012. """Exception raised by `RequestHandler.get_argument`.
  2013. This is a subclass of `HTTPError`, so if it is uncaught a 400 response
  2014. code will be used instead of 500 (and a stack trace will not be logged).
  2015. .. versionadded:: 3.1
  2016. """
  2017. def __init__(self, arg_name: str) -> None:
  2018. super(MissingArgumentError, self).__init__(
  2019. 400, "Missing argument %s" % arg_name
  2020. )
  2021. self.arg_name = arg_name
  2022. class ErrorHandler(RequestHandler):
  2023. """Generates an error response with ``status_code`` for all requests."""
  2024. def initialize(self, status_code: int) -> None:
  2025. self.set_status(status_code)
  2026. def prepare(self) -> None:
  2027. raise HTTPError(self._status_code)
  2028. def check_xsrf_cookie(self) -> None:
  2029. # POSTs to an ErrorHandler don't actually have side effects,
  2030. # so we don't need to check the xsrf token. This allows POSTs
  2031. # to the wrong url to return a 404 instead of 403.
  2032. pass
  2033. class RedirectHandler(RequestHandler):
  2034. """Redirects the client to the given URL for all GET requests.
  2035. You should provide the keyword argument ``url`` to the handler, e.g.::
  2036. application = web.Application([
  2037. (r"/oldpath", web.RedirectHandler, {"url": "/newpath"}),
  2038. ])
  2039. `RedirectHandler` supports regular expression substitutions. E.g., to
  2040. swap the first and second parts of a path while preserving the remainder::
  2041. application = web.Application([
  2042. (r"/(.*?)/(.*?)/(.*)", web.RedirectHandler, {"url": "/{1}/{0}/{2}"}),
  2043. ])
  2044. The final URL is formatted with `str.format` and the substrings that match
  2045. the capturing groups. In the above example, a request to "/a/b/c" would be
  2046. formatted like::
  2047. str.format("/{1}/{0}/{2}", "a", "b", "c") # -> "/b/a/c"
  2048. Use Python's :ref:`format string syntax <formatstrings>` to customize how
  2049. values are substituted.
  2050. .. versionchanged:: 4.5
  2051. Added support for substitutions into the destination URL.
  2052. .. versionchanged:: 5.0
  2053. If any query arguments are present, they will be copied to the
  2054. destination URL.
  2055. """
  2056. def initialize(self, url: str, permanent: bool = True) -> None:
  2057. self._url = url
  2058. self._permanent = permanent
  2059. def get(self, *args: Any) -> None:
  2060. to_url = self._url.format(*args)
  2061. if self.request.query_arguments:
  2062. # TODO: figure out typing for the next line.
  2063. to_url = httputil.url_concat(
  2064. to_url,
  2065. list(httputil.qs_to_qsl(self.request.query_arguments)), # type: ignore
  2066. )
  2067. self.redirect(to_url, permanent=self._permanent)
  2068. class StaticFileHandler(RequestHandler):
  2069. """A simple handler that can serve static content from a directory.
  2070. A `StaticFileHandler` is configured automatically if you pass the
  2071. ``static_path`` keyword argument to `Application`. This handler
  2072. can be customized with the ``static_url_prefix``, ``static_handler_class``,
  2073. and ``static_handler_args`` settings.
  2074. To map an additional path to this handler for a static data directory
  2075. you would add a line to your application like::
  2076. application = web.Application([
  2077. (r"/content/(.*)", web.StaticFileHandler, {"path": "/var/www"}),
  2078. ])
  2079. The handler constructor requires a ``path`` argument, which specifies the
  2080. local root directory of the content to be served.
  2081. Note that a capture group in the regex is required to parse the value for
  2082. the ``path`` argument to the get() method (different than the constructor
  2083. argument above); see `URLSpec` for details.
  2084. To serve a file like ``index.html`` automatically when a directory is
  2085. requested, set ``static_handler_args=dict(default_filename="index.html")``
  2086. in your application settings, or add ``default_filename`` as an initializer
  2087. argument for your ``StaticFileHandler``.
  2088. To maximize the effectiveness of browser caching, this class supports
  2089. versioned urls (by default using the argument ``?v=``). If a version
  2090. is given, we instruct the browser to cache this file indefinitely.
  2091. `make_static_url` (also available as `RequestHandler.static_url`) can
  2092. be used to construct a versioned url.
  2093. This handler is intended primarily for use in development and light-duty
  2094. file serving; for heavy traffic it will be more efficient to use
  2095. a dedicated static file server (such as nginx or Apache). We support
  2096. the HTTP ``Accept-Ranges`` mechanism to return partial content (because
  2097. some browsers require this functionality to be present to seek in
  2098. HTML5 audio or video).
  2099. **Subclassing notes**
  2100. This class is designed to be extensible by subclassing, but because
  2101. of the way static urls are generated with class methods rather than
  2102. instance methods, the inheritance patterns are somewhat unusual.
  2103. Be sure to use the ``@classmethod`` decorator when overriding a
  2104. class method. Instance methods may use the attributes ``self.path``
  2105. ``self.absolute_path``, and ``self.modified``.
  2106. Subclasses should only override methods discussed in this section;
  2107. overriding other methods is error-prone. Overriding
  2108. ``StaticFileHandler.get`` is particularly problematic due to the
  2109. tight coupling with ``compute_etag`` and other methods.
  2110. To change the way static urls are generated (e.g. to match the behavior
  2111. of another server or CDN), override `make_static_url`, `parse_url_path`,
  2112. `get_cache_time`, and/or `get_version`.
  2113. To replace all interaction with the filesystem (e.g. to serve
  2114. static content from a database), override `get_content`,
  2115. `get_content_size`, `get_modified_time`, `get_absolute_path`, and
  2116. `validate_absolute_path`.
  2117. .. versionchanged:: 3.1
  2118. Many of the methods for subclasses were added in Tornado 3.1.
  2119. """
  2120. CACHE_MAX_AGE = 86400 * 365 * 10 # 10 years
  2121. _static_hashes = {} # type: Dict[str, Optional[str]]
  2122. _lock = threading.Lock() # protects _static_hashes
  2123. def initialize(self, path: str, default_filename: str = None) -> None:
  2124. self.root = path
  2125. self.default_filename = default_filename
  2126. @classmethod
  2127. def reset(cls) -> None:
  2128. with cls._lock:
  2129. cls._static_hashes = {}
  2130. def head(self, path: str) -> Awaitable[None]:
  2131. return self.get(path, include_body=False)
  2132. async def get(self, path: str, include_body: bool = True) -> None:
  2133. # Set up our path instance variables.
  2134. self.path = self.parse_url_path(path)
  2135. del path # make sure we don't refer to path instead of self.path again
  2136. absolute_path = self.get_absolute_path(self.root, self.path)
  2137. self.absolute_path = self.validate_absolute_path(self.root, absolute_path)
  2138. if self.absolute_path is None:
  2139. return
  2140. self.modified = self.get_modified_time()
  2141. self.set_headers()
  2142. if self.should_return_304():
  2143. self.set_status(304)
  2144. return
  2145. request_range = None
  2146. range_header = self.request.headers.get("Range")
  2147. if range_header:
  2148. # As per RFC 2616 14.16, if an invalid Range header is specified,
  2149. # the request will be treated as if the header didn't exist.
  2150. request_range = httputil._parse_request_range(range_header)
  2151. size = self.get_content_size()
  2152. if request_range:
  2153. start, end = request_range
  2154. if start is not None and start < 0:
  2155. start += size
  2156. if start < 0:
  2157. start = 0
  2158. if (
  2159. start is not None
  2160. and (start >= size or (end is not None and start >= end))
  2161. ) or end == 0:
  2162. # As per RFC 2616 14.35.1, a range is not satisfiable only: if
  2163. # the first requested byte is equal to or greater than the
  2164. # content, or when a suffix with length 0 is specified.
  2165. # https://tools.ietf.org/html/rfc7233#section-2.1
  2166. # A byte-range-spec is invalid if the last-byte-pos value is present
  2167. # and less than the first-byte-pos.
  2168. self.set_status(416) # Range Not Satisfiable
  2169. self.set_header("Content-Type", "text/plain")
  2170. self.set_header("Content-Range", "bytes */%s" % (size,))
  2171. return
  2172. if end is not None and end > size:
  2173. # Clients sometimes blindly use a large range to limit their
  2174. # download size; cap the endpoint at the actual file size.
  2175. end = size
  2176. # Note: only return HTTP 206 if less than the entire range has been
  2177. # requested. Not only is this semantically correct, but Chrome
  2178. # refuses to play audio if it gets an HTTP 206 in response to
  2179. # ``Range: bytes=0-``.
  2180. if size != (end or size) - (start or 0):
  2181. self.set_status(206) # Partial Content
  2182. self.set_header(
  2183. "Content-Range", httputil._get_content_range(start, end, size)
  2184. )
  2185. else:
  2186. start = end = None
  2187. if start is not None and end is not None:
  2188. content_length = end - start
  2189. elif end is not None:
  2190. content_length = end
  2191. elif start is not None:
  2192. content_length = size - start
  2193. else:
  2194. content_length = size
  2195. self.set_header("Content-Length", content_length)
  2196. if include_body:
  2197. content = self.get_content(self.absolute_path, start, end)
  2198. if isinstance(content, bytes):
  2199. content = [content]
  2200. for chunk in content:
  2201. try:
  2202. self.write(chunk)
  2203. await self.flush()
  2204. except iostream.StreamClosedError:
  2205. return
  2206. else:
  2207. assert self.request.method == "HEAD"
  2208. def compute_etag(self) -> Optional[str]:
  2209. """Sets the ``Etag`` header based on static url version.
  2210. This allows efficient ``If-None-Match`` checks against cached
  2211. versions, and sends the correct ``Etag`` for a partial response
  2212. (i.e. the same ``Etag`` as the full file).
  2213. .. versionadded:: 3.1
  2214. """
  2215. assert self.absolute_path is not None
  2216. version_hash = self._get_cached_version(self.absolute_path)
  2217. if not version_hash:
  2218. return None
  2219. return '"%s"' % (version_hash,)
  2220. def set_headers(self) -> None:
  2221. """Sets the content and caching headers on the response.
  2222. .. versionadded:: 3.1
  2223. """
  2224. self.set_header("Accept-Ranges", "bytes")
  2225. self.set_etag_header()
  2226. if self.modified is not None:
  2227. self.set_header("Last-Modified", self.modified)
  2228. content_type = self.get_content_type()
  2229. if content_type:
  2230. self.set_header("Content-Type", content_type)
  2231. cache_time = self.get_cache_time(self.path, self.modified, content_type)
  2232. if cache_time > 0:
  2233. self.set_header(
  2234. "Expires",
  2235. datetime.datetime.utcnow() + datetime.timedelta(seconds=cache_time),
  2236. )
  2237. self.set_header("Cache-Control", "max-age=" + str(cache_time))
  2238. self.set_extra_headers(self.path)
  2239. def should_return_304(self) -> bool:
  2240. """Returns True if the headers indicate that we should return 304.
  2241. .. versionadded:: 3.1
  2242. """
  2243. # If client sent If-None-Match, use it, ignore If-Modified-Since
  2244. if self.request.headers.get("If-None-Match"):
  2245. return self.check_etag_header()
  2246. # Check the If-Modified-Since, and don't send the result if the
  2247. # content has not been modified
  2248. ims_value = self.request.headers.get("If-Modified-Since")
  2249. if ims_value is not None:
  2250. date_tuple = email.utils.parsedate(ims_value)
  2251. if date_tuple is not None:
  2252. if_since = datetime.datetime(*date_tuple[:6])
  2253. assert self.modified is not None
  2254. if if_since >= self.modified:
  2255. return True
  2256. return False
  2257. @classmethod
  2258. def get_absolute_path(cls, root: str, path: str) -> str:
  2259. """Returns the absolute location of ``path`` relative to ``root``.
  2260. ``root`` is the path configured for this `StaticFileHandler`
  2261. (in most cases the ``static_path`` `Application` setting).
  2262. This class method may be overridden in subclasses. By default
  2263. it returns a filesystem path, but other strings may be used
  2264. as long as they are unique and understood by the subclass's
  2265. overridden `get_content`.
  2266. .. versionadded:: 3.1
  2267. """
  2268. abspath = os.path.abspath(os.path.join(root, path))
  2269. return abspath
  2270. def validate_absolute_path(self, root: str, absolute_path: str) -> Optional[str]:
  2271. """Validate and return the absolute path.
  2272. ``root`` is the configured path for the `StaticFileHandler`,
  2273. and ``path`` is the result of `get_absolute_path`
  2274. This is an instance method called during request processing,
  2275. so it may raise `HTTPError` or use methods like
  2276. `RequestHandler.redirect` (return None after redirecting to
  2277. halt further processing). This is where 404 errors for missing files
  2278. are generated.
  2279. This method may modify the path before returning it, but note that
  2280. any such modifications will not be understood by `make_static_url`.
  2281. In instance methods, this method's result is available as
  2282. ``self.absolute_path``.
  2283. .. versionadded:: 3.1
  2284. """
  2285. # os.path.abspath strips a trailing /.
  2286. # We must add it back to `root` so that we only match files
  2287. # in a directory named `root` instead of files starting with
  2288. # that prefix.
  2289. root = os.path.abspath(root)
  2290. if not root.endswith(os.path.sep):
  2291. # abspath always removes a trailing slash, except when
  2292. # root is '/'. This is an unusual case, but several projects
  2293. # have independently discovered this technique to disable
  2294. # Tornado's path validation and (hopefully) do their own,
  2295. # so we need to support it.
  2296. root += os.path.sep
  2297. # The trailing slash also needs to be temporarily added back
  2298. # the requested path so a request to root/ will match.
  2299. if not (absolute_path + os.path.sep).startswith(root):
  2300. raise HTTPError(403, "%s is not in root static directory", self.path)
  2301. if os.path.isdir(absolute_path) and self.default_filename is not None:
  2302. # need to look at the request.path here for when path is empty
  2303. # but there is some prefix to the path that was already
  2304. # trimmed by the routing
  2305. if not self.request.path.endswith("/"):
  2306. self.redirect(self.request.path + "/", permanent=True)
  2307. return None
  2308. absolute_path = os.path.join(absolute_path, self.default_filename)
  2309. if not os.path.exists(absolute_path):
  2310. raise HTTPError(404)
  2311. if not os.path.isfile(absolute_path):
  2312. raise HTTPError(403, "%s is not a file", self.path)
  2313. return absolute_path
  2314. @classmethod
  2315. def get_content(
  2316. cls, abspath: str, start: int = None, end: int = None
  2317. ) -> Generator[bytes, None, None]:
  2318. """Retrieve the content of the requested resource which is located
  2319. at the given absolute path.
  2320. This class method may be overridden by subclasses. Note that its
  2321. signature is different from other overridable class methods
  2322. (no ``settings`` argument); this is deliberate to ensure that
  2323. ``abspath`` is able to stand on its own as a cache key.
  2324. This method should either return a byte string or an iterator
  2325. of byte strings. The latter is preferred for large files
  2326. as it helps reduce memory fragmentation.
  2327. .. versionadded:: 3.1
  2328. """
  2329. with open(abspath, "rb") as file:
  2330. if start is not None:
  2331. file.seek(start)
  2332. if end is not None:
  2333. remaining = end - (start or 0) # type: Optional[int]
  2334. else:
  2335. remaining = None
  2336. while True:
  2337. chunk_size = 64 * 1024
  2338. if remaining is not None and remaining < chunk_size:
  2339. chunk_size = remaining
  2340. chunk = file.read(chunk_size)
  2341. if chunk:
  2342. if remaining is not None:
  2343. remaining -= len(chunk)
  2344. yield chunk
  2345. else:
  2346. if remaining is not None:
  2347. assert remaining == 0
  2348. return
  2349. @classmethod
  2350. def get_content_version(cls, abspath: str) -> str:
  2351. """Returns a version string for the resource at the given path.
  2352. This class method may be overridden by subclasses. The
  2353. default implementation is a hash of the file's contents.
  2354. .. versionadded:: 3.1
  2355. """
  2356. data = cls.get_content(abspath)
  2357. hasher = hashlib.md5()
  2358. if isinstance(data, bytes):
  2359. hasher.update(data)
  2360. else:
  2361. for chunk in data:
  2362. hasher.update(chunk)
  2363. return hasher.hexdigest()
  2364. def _stat(self) -> os.stat_result:
  2365. assert self.absolute_path is not None
  2366. if not hasattr(self, "_stat_result"):
  2367. self._stat_result = os.stat(self.absolute_path)
  2368. return self._stat_result
  2369. def get_content_size(self) -> int:
  2370. """Retrieve the total size of the resource at the given path.
  2371. This method may be overridden by subclasses.
  2372. .. versionadded:: 3.1
  2373. .. versionchanged:: 4.0
  2374. This method is now always called, instead of only when
  2375. partial results are requested.
  2376. """
  2377. stat_result = self._stat()
  2378. return stat_result.st_size
  2379. def get_modified_time(self) -> Optional[datetime.datetime]:
  2380. """Returns the time that ``self.absolute_path`` was last modified.
  2381. May be overridden in subclasses. Should return a `~datetime.datetime`
  2382. object or None.
  2383. .. versionadded:: 3.1
  2384. """
  2385. stat_result = self._stat()
  2386. # NOTE: Historically, this used stat_result[stat.ST_MTIME],
  2387. # which truncates the fractional portion of the timestamp. It
  2388. # was changed from that form to stat_result.st_mtime to
  2389. # satisfy mypy (which disallows the bracket operator), but the
  2390. # latter form returns a float instead of an int. For
  2391. # consistency with the past (and because we have a unit test
  2392. # that relies on this), we truncate the float here, although
  2393. # I'm not sure that's the right thing to do.
  2394. modified = datetime.datetime.utcfromtimestamp(int(stat_result.st_mtime))
  2395. return modified
  2396. def get_content_type(self) -> str:
  2397. """Returns the ``Content-Type`` header to be used for this request.
  2398. .. versionadded:: 3.1
  2399. """
  2400. assert self.absolute_path is not None
  2401. mime_type, encoding = mimetypes.guess_type(self.absolute_path)
  2402. # per RFC 6713, use the appropriate type for a gzip compressed file
  2403. if encoding == "gzip":
  2404. return "application/gzip"
  2405. # As of 2015-07-21 there is no bzip2 encoding defined at
  2406. # http://www.iana.org/assignments/media-types/media-types.xhtml
  2407. # So for that (and any other encoding), use octet-stream.
  2408. elif encoding is not None:
  2409. return "application/octet-stream"
  2410. elif mime_type is not None:
  2411. return mime_type
  2412. # if mime_type not detected, use application/octet-stream
  2413. else:
  2414. return "application/octet-stream"
  2415. def set_extra_headers(self, path: str) -> None:
  2416. """For subclass to add extra headers to the response"""
  2417. pass
  2418. def get_cache_time(
  2419. self, path: str, modified: Optional[datetime.datetime], mime_type: str
  2420. ) -> int:
  2421. """Override to customize cache control behavior.
  2422. Return a positive number of seconds to make the result
  2423. cacheable for that amount of time or 0 to mark resource as
  2424. cacheable for an unspecified amount of time (subject to
  2425. browser heuristics).
  2426. By default returns cache expiry of 10 years for resources requested
  2427. with ``v`` argument.
  2428. """
  2429. return self.CACHE_MAX_AGE if "v" in self.request.arguments else 0
  2430. @classmethod
  2431. def make_static_url(
  2432. cls, settings: Dict[str, Any], path: str, include_version: bool = True
  2433. ) -> str:
  2434. """Constructs a versioned url for the given path.
  2435. This method may be overridden in subclasses (but note that it
  2436. is a class method rather than an instance method). Subclasses
  2437. are only required to implement the signature
  2438. ``make_static_url(cls, settings, path)``; other keyword
  2439. arguments may be passed through `~RequestHandler.static_url`
  2440. but are not standard.
  2441. ``settings`` is the `Application.settings` dictionary. ``path``
  2442. is the static path being requested. The url returned should be
  2443. relative to the current host.
  2444. ``include_version`` determines whether the generated URL should
  2445. include the query string containing the version hash of the
  2446. file corresponding to the given ``path``.
  2447. """
  2448. url = settings.get("static_url_prefix", "/static/") + path
  2449. if not include_version:
  2450. return url
  2451. version_hash = cls.get_version(settings, path)
  2452. if not version_hash:
  2453. return url
  2454. return "%s?v=%s" % (url, version_hash)
  2455. def parse_url_path(self, url_path: str) -> str:
  2456. """Converts a static URL path into a filesystem path.
  2457. ``url_path`` is the path component of the URL with
  2458. ``static_url_prefix`` removed. The return value should be
  2459. filesystem path relative to ``static_path``.
  2460. This is the inverse of `make_static_url`.
  2461. """
  2462. if os.path.sep != "/":
  2463. url_path = url_path.replace("/", os.path.sep)
  2464. return url_path
  2465. @classmethod
  2466. def get_version(cls, settings: Dict[str, Any], path: str) -> Optional[str]:
  2467. """Generate the version string to be used in static URLs.
  2468. ``settings`` is the `Application.settings` dictionary and ``path``
  2469. is the relative location of the requested asset on the filesystem.
  2470. The returned value should be a string, or ``None`` if no version
  2471. could be determined.
  2472. .. versionchanged:: 3.1
  2473. This method was previously recommended for subclasses to override;
  2474. `get_content_version` is now preferred as it allows the base
  2475. class to handle caching of the result.
  2476. """
  2477. abs_path = cls.get_absolute_path(settings["static_path"], path)
  2478. return cls._get_cached_version(abs_path)
  2479. @classmethod
  2480. def _get_cached_version(cls, abs_path: str) -> Optional[str]:
  2481. with cls._lock:
  2482. hashes = cls._static_hashes
  2483. if abs_path not in hashes:
  2484. try:
  2485. hashes[abs_path] = cls.get_content_version(abs_path)
  2486. except Exception:
  2487. gen_log.error("Could not open static file %r", abs_path)
  2488. hashes[abs_path] = None
  2489. hsh = hashes.get(abs_path)
  2490. if hsh:
  2491. return hsh
  2492. return None
  2493. class FallbackHandler(RequestHandler):
  2494. """A `RequestHandler` that wraps another HTTP server callback.
  2495. The fallback is a callable object that accepts an
  2496. `~.httputil.HTTPServerRequest`, such as an `Application` or
  2497. `tornado.wsgi.WSGIContainer`. This is most useful to use both
  2498. Tornado ``RequestHandlers`` and WSGI in the same server. Typical
  2499. usage::
  2500. wsgi_app = tornado.wsgi.WSGIContainer(
  2501. django.core.handlers.wsgi.WSGIHandler())
  2502. application = tornado.web.Application([
  2503. (r"/foo", FooHandler),
  2504. (r".*", FallbackHandler, dict(fallback=wsgi_app),
  2505. ])
  2506. """
  2507. def initialize(
  2508. self, fallback: Callable[[httputil.HTTPServerRequest], None]
  2509. ) -> None:
  2510. self.fallback = fallback
  2511. def prepare(self) -> None:
  2512. self.fallback(self.request)
  2513. self._finished = True
  2514. self.on_finish()
  2515. class OutputTransform(object):
  2516. """A transform modifies the result of an HTTP request (e.g., GZip encoding)
  2517. Applications are not expected to create their own OutputTransforms
  2518. or interact with them directly; the framework chooses which transforms
  2519. (if any) to apply.
  2520. """
  2521. def __init__(self, request: httputil.HTTPServerRequest) -> None:
  2522. pass
  2523. def transform_first_chunk(
  2524. self,
  2525. status_code: int,
  2526. headers: httputil.HTTPHeaders,
  2527. chunk: bytes,
  2528. finishing: bool,
  2529. ) -> Tuple[int, httputil.HTTPHeaders, bytes]:
  2530. return status_code, headers, chunk
  2531. def transform_chunk(self, chunk: bytes, finishing: bool) -> bytes:
  2532. return chunk
  2533. class GZipContentEncoding(OutputTransform):
  2534. """Applies the gzip content encoding to the response.
  2535. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11
  2536. .. versionchanged:: 4.0
  2537. Now compresses all mime types beginning with ``text/``, instead
  2538. of just a whitelist. (the whitelist is still used for certain
  2539. non-text mime types).
  2540. """
  2541. # Whitelist of compressible mime types (in addition to any types
  2542. # beginning with "text/").
  2543. CONTENT_TYPES = set(
  2544. [
  2545. "application/javascript",
  2546. "application/x-javascript",
  2547. "application/xml",
  2548. "application/atom+xml",
  2549. "application/json",
  2550. "application/xhtml+xml",
  2551. "image/svg+xml",
  2552. ]
  2553. )
  2554. # Python's GzipFile defaults to level 9, while most other gzip
  2555. # tools (including gzip itself) default to 6, which is probably a
  2556. # better CPU/size tradeoff.
  2557. GZIP_LEVEL = 6
  2558. # Responses that are too short are unlikely to benefit from gzipping
  2559. # after considering the "Content-Encoding: gzip" header and the header
  2560. # inside the gzip encoding.
  2561. # Note that responses written in multiple chunks will be compressed
  2562. # regardless of size.
  2563. MIN_LENGTH = 1024
  2564. def __init__(self, request: httputil.HTTPServerRequest) -> None:
  2565. self._gzipping = "gzip" in request.headers.get("Accept-Encoding", "")
  2566. def _compressible_type(self, ctype: str) -> bool:
  2567. return ctype.startswith("text/") or ctype in self.CONTENT_TYPES
  2568. def transform_first_chunk(
  2569. self,
  2570. status_code: int,
  2571. headers: httputil.HTTPHeaders,
  2572. chunk: bytes,
  2573. finishing: bool,
  2574. ) -> Tuple[int, httputil.HTTPHeaders, bytes]:
  2575. # TODO: can/should this type be inherited from the superclass?
  2576. if "Vary" in headers:
  2577. headers["Vary"] += ", Accept-Encoding"
  2578. else:
  2579. headers["Vary"] = "Accept-Encoding"
  2580. if self._gzipping:
  2581. ctype = _unicode(headers.get("Content-Type", "")).split(";")[0]
  2582. self._gzipping = (
  2583. self._compressible_type(ctype)
  2584. and (not finishing or len(chunk) >= self.MIN_LENGTH)
  2585. and ("Content-Encoding" not in headers)
  2586. )
  2587. if self._gzipping:
  2588. headers["Content-Encoding"] = "gzip"
  2589. self._gzip_value = BytesIO()
  2590. self._gzip_file = gzip.GzipFile(
  2591. mode="w", fileobj=self._gzip_value, compresslevel=self.GZIP_LEVEL
  2592. )
  2593. chunk = self.transform_chunk(chunk, finishing)
  2594. if "Content-Length" in headers:
  2595. # The original content length is no longer correct.
  2596. # If this is the last (and only) chunk, we can set the new
  2597. # content-length; otherwise we remove it and fall back to
  2598. # chunked encoding.
  2599. if finishing:
  2600. headers["Content-Length"] = str(len(chunk))
  2601. else:
  2602. del headers["Content-Length"]
  2603. return status_code, headers, chunk
  2604. def transform_chunk(self, chunk: bytes, finishing: bool) -> bytes:
  2605. if self._gzipping:
  2606. self._gzip_file.write(chunk)
  2607. if finishing:
  2608. self._gzip_file.close()
  2609. else:
  2610. self._gzip_file.flush()
  2611. chunk = self._gzip_value.getvalue()
  2612. self._gzip_value.truncate(0)
  2613. self._gzip_value.seek(0)
  2614. return chunk
  2615. def authenticated(
  2616. method: Callable[..., Optional[Awaitable[None]]]
  2617. ) -> Callable[..., Optional[Awaitable[None]]]:
  2618. """Decorate methods with this to require that the user be logged in.
  2619. If the user is not logged in, they will be redirected to the configured
  2620. `login url <RequestHandler.get_login_url>`.
  2621. If you configure a login url with a query parameter, Tornado will
  2622. assume you know what you're doing and use it as-is. If not, it
  2623. will add a `next` parameter so the login page knows where to send
  2624. you once you're logged in.
  2625. """
  2626. @functools.wraps(method)
  2627. def wrapper( # type: ignore
  2628. self: RequestHandler, *args, **kwargs
  2629. ) -> Optional[Awaitable[None]]:
  2630. if not self.current_user:
  2631. if self.request.method in ("GET", "HEAD"):
  2632. url = self.get_login_url()
  2633. if "?" not in url:
  2634. if urllib.parse.urlsplit(url).scheme:
  2635. # if login url is absolute, make next absolute too
  2636. next_url = self.request.full_url()
  2637. else:
  2638. assert self.request.uri is not None
  2639. next_url = self.request.uri
  2640. url += "?" + urlencode(dict(next=next_url))
  2641. self.redirect(url)
  2642. return None
  2643. raise HTTPError(403)
  2644. return method(self, *args, **kwargs)
  2645. return wrapper
  2646. class UIModule(object):
  2647. """A re-usable, modular UI unit on a page.
  2648. UI modules often execute additional queries, and they can include
  2649. additional CSS and JavaScript that will be included in the output
  2650. page, which is automatically inserted on page render.
  2651. Subclasses of UIModule must override the `render` method.
  2652. """
  2653. def __init__(self, handler: RequestHandler) -> None:
  2654. self.handler = handler
  2655. self.request = handler.request
  2656. self.ui = handler.ui
  2657. self.locale = handler.locale
  2658. @property
  2659. def current_user(self) -> Any:
  2660. return self.handler.current_user
  2661. def render(self, *args: Any, **kwargs: Any) -> str:
  2662. """Override in subclasses to return this module's output."""
  2663. raise NotImplementedError()
  2664. def embedded_javascript(self) -> Optional[str]:
  2665. """Override to return a JavaScript string
  2666. to be embedded in the page."""
  2667. return None
  2668. def javascript_files(self) -> Optional[Iterable[str]]:
  2669. """Override to return a list of JavaScript files needed by this module.
  2670. If the return values are relative paths, they will be passed to
  2671. `RequestHandler.static_url`; otherwise they will be used as-is.
  2672. """
  2673. return None
  2674. def embedded_css(self) -> Optional[str]:
  2675. """Override to return a CSS string
  2676. that will be embedded in the page."""
  2677. return None
  2678. def css_files(self) -> Optional[Iterable[str]]:
  2679. """Override to returns a list of CSS files required by this module.
  2680. If the return values are relative paths, they will be passed to
  2681. `RequestHandler.static_url`; otherwise they will be used as-is.
  2682. """
  2683. return None
  2684. def html_head(self) -> Optional[str]:
  2685. """Override to return an HTML string that will be put in the <head/>
  2686. element.
  2687. """
  2688. return None
  2689. def html_body(self) -> Optional[str]:
  2690. """Override to return an HTML string that will be put at the end of
  2691. the <body/> element.
  2692. """
  2693. return None
  2694. def render_string(self, path: str, **kwargs: Any) -> bytes:
  2695. """Renders a template and returns it as a string."""
  2696. return self.handler.render_string(path, **kwargs)
  2697. class _linkify(UIModule):
  2698. def render(self, text: str, **kwargs: Any) -> str: # type: ignore
  2699. return escape.linkify(text, **kwargs)
  2700. class _xsrf_form_html(UIModule):
  2701. def render(self) -> str: # type: ignore
  2702. return self.handler.xsrf_form_html()
  2703. class TemplateModule(UIModule):
  2704. """UIModule that simply renders the given template.
  2705. {% module Template("foo.html") %} is similar to {% include "foo.html" %},
  2706. but the module version gets its own namespace (with kwargs passed to
  2707. Template()) instead of inheriting the outer template's namespace.
  2708. Templates rendered through this module also get access to UIModule's
  2709. automatic javascript/css features. Simply call set_resources
  2710. inside the template and give it keyword arguments corresponding to
  2711. the methods on UIModule: {{ set_resources(js_files=static_url("my.js")) }}
  2712. Note that these resources are output once per template file, not once
  2713. per instantiation of the template, so they must not depend on
  2714. any arguments to the template.
  2715. """
  2716. def __init__(self, handler: RequestHandler) -> None:
  2717. super(TemplateModule, self).__init__(handler)
  2718. # keep resources in both a list and a dict to preserve order
  2719. self._resource_list = [] # type: List[Dict[str, Any]]
  2720. self._resource_dict = {} # type: Dict[str, Dict[str, Any]]
  2721. def render(self, path: str, **kwargs: Any) -> bytes: # type: ignore
  2722. def set_resources(**kwargs) -> str: # type: ignore
  2723. if path not in self._resource_dict:
  2724. self._resource_list.append(kwargs)
  2725. self._resource_dict[path] = kwargs
  2726. else:
  2727. if self._resource_dict[path] != kwargs:
  2728. raise ValueError(
  2729. "set_resources called with different "
  2730. "resources for the same template"
  2731. )
  2732. return ""
  2733. return self.render_string(path, set_resources=set_resources, **kwargs)
  2734. def _get_resources(self, key: str) -> Iterable[str]:
  2735. return (r[key] for r in self._resource_list if key in r)
  2736. def embedded_javascript(self) -> str:
  2737. return "\n".join(self._get_resources("embedded_javascript"))
  2738. def javascript_files(self) -> Iterable[str]:
  2739. result = []
  2740. for f in self._get_resources("javascript_files"):
  2741. if isinstance(f, (unicode_type, bytes)):
  2742. result.append(f)
  2743. else:
  2744. result.extend(f)
  2745. return result
  2746. def embedded_css(self) -> str:
  2747. return "\n".join(self._get_resources("embedded_css"))
  2748. def css_files(self) -> Iterable[str]:
  2749. result = []
  2750. for f in self._get_resources("css_files"):
  2751. if isinstance(f, (unicode_type, bytes)):
  2752. result.append(f)
  2753. else:
  2754. result.extend(f)
  2755. return result
  2756. def html_head(self) -> str:
  2757. return "".join(self._get_resources("html_head"))
  2758. def html_body(self) -> str:
  2759. return "".join(self._get_resources("html_body"))
  2760. class _UIModuleNamespace(object):
  2761. """Lazy namespace which creates UIModule proxies bound to a handler."""
  2762. def __init__(
  2763. self, handler: RequestHandler, ui_modules: Dict[str, Type[UIModule]]
  2764. ) -> None:
  2765. self.handler = handler
  2766. self.ui_modules = ui_modules
  2767. def __getitem__(self, key: str) -> Callable[..., str]:
  2768. return self.handler._ui_module(key, self.ui_modules[key])
  2769. def __getattr__(self, key: str) -> Callable[..., str]:
  2770. try:
  2771. return self[key]
  2772. except KeyError as e:
  2773. raise AttributeError(str(e))
  2774. def create_signed_value(
  2775. secret: _CookieSecretTypes,
  2776. name: str,
  2777. value: Union[str, bytes],
  2778. version: int = None,
  2779. clock: Callable[[], float] = None,
  2780. key_version: int = None,
  2781. ) -> bytes:
  2782. if version is None:
  2783. version = DEFAULT_SIGNED_VALUE_VERSION
  2784. if clock is None:
  2785. clock = time.time
  2786. timestamp = utf8(str(int(clock())))
  2787. value = base64.b64encode(utf8(value))
  2788. if version == 1:
  2789. assert not isinstance(secret, dict)
  2790. signature = _create_signature_v1(secret, name, value, timestamp)
  2791. value = b"|".join([value, timestamp, signature])
  2792. return value
  2793. elif version == 2:
  2794. # The v2 format consists of a version number and a series of
  2795. # length-prefixed fields "%d:%s", the last of which is a
  2796. # signature, all separated by pipes. All numbers are in
  2797. # decimal format with no leading zeros. The signature is an
  2798. # HMAC-SHA256 of the whole string up to that point, including
  2799. # the final pipe.
  2800. #
  2801. # The fields are:
  2802. # - format version (i.e. 2; no length prefix)
  2803. # - key version (integer, default is 0)
  2804. # - timestamp (integer seconds since epoch)
  2805. # - name (not encoded; assumed to be ~alphanumeric)
  2806. # - value (base64-encoded)
  2807. # - signature (hex-encoded; no length prefix)
  2808. def format_field(s: Union[str, bytes]) -> bytes:
  2809. return utf8("%d:" % len(s)) + utf8(s)
  2810. to_sign = b"|".join(
  2811. [
  2812. b"2",
  2813. format_field(str(key_version or 0)),
  2814. format_field(timestamp),
  2815. format_field(name),
  2816. format_field(value),
  2817. b"",
  2818. ]
  2819. )
  2820. if isinstance(secret, dict):
  2821. assert (
  2822. key_version is not None
  2823. ), "Key version must be set when sign key dict is used"
  2824. assert version >= 2, "Version must be at least 2 for key version support"
  2825. secret = secret[key_version]
  2826. signature = _create_signature_v2(secret, to_sign)
  2827. return to_sign + signature
  2828. else:
  2829. raise ValueError("Unsupported version %d" % version)
  2830. # A leading version number in decimal
  2831. # with no leading zeros, followed by a pipe.
  2832. _signed_value_version_re = re.compile(br"^([1-9][0-9]*)\|(.*)$")
  2833. def _get_version(value: bytes) -> int:
  2834. # Figures out what version value is. Version 1 did not include an
  2835. # explicit version field and started with arbitrary base64 data,
  2836. # which makes this tricky.
  2837. m = _signed_value_version_re.match(value)
  2838. if m is None:
  2839. version = 1
  2840. else:
  2841. try:
  2842. version = int(m.group(1))
  2843. if version > 999:
  2844. # Certain payloads from the version-less v1 format may
  2845. # be parsed as valid integers. Due to base64 padding
  2846. # restrictions, this can only happen for numbers whose
  2847. # length is a multiple of 4, so we can treat all
  2848. # numbers up to 999 as versions, and for the rest we
  2849. # fall back to v1 format.
  2850. version = 1
  2851. except ValueError:
  2852. version = 1
  2853. return version
  2854. def decode_signed_value(
  2855. secret: _CookieSecretTypes,
  2856. name: str,
  2857. value: Union[None, str, bytes],
  2858. max_age_days: int = 31,
  2859. clock: Callable[[], float] = None,
  2860. min_version: int = None,
  2861. ) -> Optional[bytes]:
  2862. if clock is None:
  2863. clock = time.time
  2864. if min_version is None:
  2865. min_version = DEFAULT_SIGNED_VALUE_MIN_VERSION
  2866. if min_version > 2:
  2867. raise ValueError("Unsupported min_version %d" % min_version)
  2868. if not value:
  2869. return None
  2870. value = utf8(value)
  2871. version = _get_version(value)
  2872. if version < min_version:
  2873. return None
  2874. if version == 1:
  2875. assert not isinstance(secret, dict)
  2876. return _decode_signed_value_v1(secret, name, value, max_age_days, clock)
  2877. elif version == 2:
  2878. return _decode_signed_value_v2(secret, name, value, max_age_days, clock)
  2879. else:
  2880. return None
  2881. def _decode_signed_value_v1(
  2882. secret: Union[str, bytes],
  2883. name: str,
  2884. value: bytes,
  2885. max_age_days: int,
  2886. clock: Callable[[], float],
  2887. ) -> Optional[bytes]:
  2888. parts = utf8(value).split(b"|")
  2889. if len(parts) != 3:
  2890. return None
  2891. signature = _create_signature_v1(secret, name, parts[0], parts[1])
  2892. if not hmac.compare_digest(parts[2], signature):
  2893. gen_log.warning("Invalid cookie signature %r", value)
  2894. return None
  2895. timestamp = int(parts[1])
  2896. if timestamp < clock() - max_age_days * 86400:
  2897. gen_log.warning("Expired cookie %r", value)
  2898. return None
  2899. if timestamp > clock() + 31 * 86400:
  2900. # _cookie_signature does not hash a delimiter between the
  2901. # parts of the cookie, so an attacker could transfer trailing
  2902. # digits from the payload to the timestamp without altering the
  2903. # signature. For backwards compatibility, sanity-check timestamp
  2904. # here instead of modifying _cookie_signature.
  2905. gen_log.warning("Cookie timestamp in future; possible tampering %r", value)
  2906. return None
  2907. if parts[1].startswith(b"0"):
  2908. gen_log.warning("Tampered cookie %r", value)
  2909. return None
  2910. try:
  2911. return base64.b64decode(parts[0])
  2912. except Exception:
  2913. return None
  2914. def _decode_fields_v2(value: bytes) -> Tuple[int, bytes, bytes, bytes, bytes]:
  2915. def _consume_field(s: bytes) -> Tuple[bytes, bytes]:
  2916. length, _, rest = s.partition(b":")
  2917. n = int(length)
  2918. field_value = rest[:n]
  2919. # In python 3, indexing bytes returns small integers; we must
  2920. # use a slice to get a byte string as in python 2.
  2921. if rest[n : n + 1] != b"|":
  2922. raise ValueError("malformed v2 signed value field")
  2923. rest = rest[n + 1 :]
  2924. return field_value, rest
  2925. rest = value[2:] # remove version number
  2926. key_version, rest = _consume_field(rest)
  2927. timestamp, rest = _consume_field(rest)
  2928. name_field, rest = _consume_field(rest)
  2929. value_field, passed_sig = _consume_field(rest)
  2930. return int(key_version), timestamp, name_field, value_field, passed_sig
  2931. def _decode_signed_value_v2(
  2932. secret: _CookieSecretTypes,
  2933. name: str,
  2934. value: bytes,
  2935. max_age_days: int,
  2936. clock: Callable[[], float],
  2937. ) -> Optional[bytes]:
  2938. try:
  2939. (
  2940. key_version,
  2941. timestamp_bytes,
  2942. name_field,
  2943. value_field,
  2944. passed_sig,
  2945. ) = _decode_fields_v2(value)
  2946. except ValueError:
  2947. return None
  2948. signed_string = value[: -len(passed_sig)]
  2949. if isinstance(secret, dict):
  2950. try:
  2951. secret = secret[key_version]
  2952. except KeyError:
  2953. return None
  2954. expected_sig = _create_signature_v2(secret, signed_string)
  2955. if not hmac.compare_digest(passed_sig, expected_sig):
  2956. return None
  2957. if name_field != utf8(name):
  2958. return None
  2959. timestamp = int(timestamp_bytes)
  2960. if timestamp < clock() - max_age_days * 86400:
  2961. # The signature has expired.
  2962. return None
  2963. try:
  2964. return base64.b64decode(value_field)
  2965. except Exception:
  2966. return None
  2967. def get_signature_key_version(value: Union[str, bytes]) -> Optional[int]:
  2968. value = utf8(value)
  2969. version = _get_version(value)
  2970. if version < 2:
  2971. return None
  2972. try:
  2973. key_version, _, _, _, _ = _decode_fields_v2(value)
  2974. except ValueError:
  2975. return None
  2976. return key_version
  2977. def _create_signature_v1(secret: Union[str, bytes], *parts: Union[str, bytes]) -> bytes:
  2978. hash = hmac.new(utf8(secret), digestmod=hashlib.sha1)
  2979. for part in parts:
  2980. hash.update(utf8(part))
  2981. return utf8(hash.hexdigest())
  2982. def _create_signature_v2(secret: Union[str, bytes], s: bytes) -> bytes:
  2983. hash = hmac.new(utf8(secret), digestmod=hashlib.sha256)
  2984. hash.update(utf8(s))
  2985. return utf8(hash.hexdigest())
  2986. def is_absolute(path: str) -> bool:
  2987. return any(path.startswith(x) for x in ["/", "http:", "https:"])