web.py 130 KB

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