bottle.py 151 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. Bottle is a fast and simple micro-framework for small web applications. It
  5. offers request dispatching (Routes) with url parameter support, templates,
  6. a built-in HTTP Server and adapters for many third party WSGI/HTTP-server and
  7. template engines - all in a single file and with no dependencies other than the
  8. Python Standard Library.
  9. Homepage and documentation: http://bottlepy.org/
  10. Copyright (c) 2016, Marcel Hellkamp.
  11. License: MIT (see LICENSE for details)
  12. 适用于Umi-OCR项目的Bottle,经由hiroi-sora修改。
  13. 遵守原作者的开源协议,修改和定制同样遵循原协议。
  14. """
  15. from __future__ import with_statement
  16. __author__ = "Marcel Hellkamp"
  17. __version__ = "0.12.25"
  18. __license__ = "MIT"
  19. # The gevent server adapter needs to patch some modules before they are imported
  20. # This is why we parse the commandline parameters here but handle them later
  21. if __name__ == "__main__":
  22. from optparse import OptionParser
  23. _cmd_parser = OptionParser(usage="usage: %prog [options] package.module:app")
  24. _opt = _cmd_parser.add_option
  25. _opt("--version", action="store_true", help="show version number.")
  26. _opt("-b", "--bind", metavar="ADDRESS", help="bind socket to ADDRESS.")
  27. _opt("-s", "--server", default="wsgiref", help="use SERVER as backend.")
  28. _opt("-p", "--plugin", action="append", help="install additional plugin/s.")
  29. _opt("--debug", action="store_true", help="start server in debug mode.")
  30. _opt("--reload", action="store_true", help="auto-reload on file changes.")
  31. _cmd_options, _cmd_args = _cmd_parser.parse_args()
  32. if _cmd_options.server and _cmd_options.server.startswith("gevent"):
  33. import gevent.monkey
  34. gevent.monkey.patch_all()
  35. import base64, cgi, email.utils, functools, hmac, itertools, mimetypes, os, re, subprocess, sys, tempfile, threading, time, warnings, hashlib
  36. from datetime import date as datedate, datetime, timedelta
  37. from tempfile import TemporaryFile
  38. from traceback import format_exc, print_exc
  39. from unicodedata import normalize
  40. try:
  41. from simplejson import dumps as json_dumps, loads as json_lds
  42. except ImportError: # pragma: no cover
  43. try:
  44. from json import dumps as json_dumps, loads as json_lds
  45. except ImportError:
  46. try:
  47. from django.utils.simplejson import dumps as json_dumps, loads as json_lds
  48. except ImportError:
  49. def json_dumps(data):
  50. raise ImportError("JSON support requires Python 2.6 or simplejson.")
  51. json_lds = json_dumps
  52. # We now try to fix 2.5/2.6/3.1/3.2 incompatibilities.
  53. # It ain't pretty but it works... Sorry for the mess.
  54. py = sys.version_info
  55. py3k = py >= (3, 0, 0)
  56. py25 = py < (2, 6, 0)
  57. py31 = (3, 1, 0) <= py < (3, 2, 0)
  58. # Workaround for the missing "as" keyword in py3k.
  59. def _e():
  60. return sys.exc_info()[1]
  61. # Workaround for the "print is a keyword/function" Python 2/3 dilemma
  62. # and a fallback for mod_wsgi (resticts stdout/err attribute access)
  63. try:
  64. _stdout, _stderr = sys.stdout.write, sys.stderr.write
  65. except IOError:
  66. _stdout = lambda x: sys.stdout.write(x)
  67. _stderr = lambda x: sys.stderr.write(x)
  68. # Lots of stdlib and builtin differences.
  69. if py3k:
  70. import http.client as httplib
  71. import _thread as thread
  72. from urllib.parse import urljoin, SplitResult as UrlSplitResult
  73. from urllib.parse import urlencode, quote as urlquote, unquote as urlunquote
  74. urlunquote = functools.partial(urlunquote, encoding="latin1")
  75. from http.cookies import SimpleCookie
  76. if py >= (3, 3, 0):
  77. from collections.abc import MutableMapping as DictMixin
  78. from types import ModuleType as new_module
  79. else:
  80. from collections import MutableMapping as DictMixin
  81. from imp import new_module
  82. import pickle
  83. from io import BytesIO
  84. from configparser import ConfigParser
  85. from inspect import getfullargspec
  86. def getargspec(func):
  87. spec = getfullargspec(func)
  88. kwargs = makelist(spec[0]) + makelist(spec.kwonlyargs)
  89. return kwargs, spec[1], spec[2], spec[3]
  90. basestring = str
  91. unicode = str
  92. json_loads = lambda s: json_lds(touni(s))
  93. callable = lambda x: hasattr(x, "__call__")
  94. imap = map
  95. def _raise(*a):
  96. raise a[0](a[1]).with_traceback(a[2])
  97. else: # 2.x
  98. import httplib
  99. import thread
  100. from urlparse import urljoin, SplitResult as UrlSplitResult
  101. from urllib import urlencode, quote as urlquote, unquote as urlunquote
  102. from Cookie import SimpleCookie
  103. from itertools import imap
  104. import cPickle as pickle
  105. from imp import new_module
  106. from StringIO import StringIO as BytesIO
  107. from ConfigParser import SafeConfigParser as ConfigParser
  108. from inspect import getargspec
  109. if py25:
  110. msg = "Python 2.5 support may be dropped in future versions of Bottle."
  111. warnings.warn(msg, DeprecationWarning)
  112. from UserDict import DictMixin
  113. def next(it):
  114. return it.next()
  115. bytes = str
  116. else: # 2.6, 2.7
  117. from collections import MutableMapping as DictMixin
  118. unicode = unicode
  119. json_loads = json_lds
  120. eval(compile("def _raise(*a): raise a[0], a[1], a[2]", "<py3fix>", "exec"))
  121. # Some helpers for string/byte handling
  122. def tob(s, enc="utf8"):
  123. return s.encode(enc) if isinstance(s, unicode) else bytes(s)
  124. def touni(s, enc="utf8", err="strict"):
  125. return s.decode(enc, err) if isinstance(s, bytes) else unicode(s)
  126. tonat = touni if py3k else tob
  127. # 3.2 fixes cgi.FieldStorage to accept bytes (which makes a lot of sense).
  128. # 3.1 needs a workaround.
  129. if py31:
  130. from io import TextIOWrapper
  131. class NCTextIOWrapper(TextIOWrapper):
  132. def close(self):
  133. pass # Keep wrapped buffer open.
  134. # A bug in functools causes it to break if the wrapper is an instance method
  135. def update_wrapper(wrapper, wrapped, *a, **ka):
  136. try:
  137. functools.update_wrapper(wrapper, wrapped, *a, **ka)
  138. except AttributeError:
  139. pass
  140. # These helpers are used at module level and need to be defined first.
  141. # And yes, I know PEP-8, but sometimes a lower-case classname makes more sense.
  142. def depr(message, hard=False):
  143. warnings.warn(message, DeprecationWarning, stacklevel=3)
  144. def makelist(data): # This is just to handy
  145. if isinstance(data, (tuple, list, set, dict)):
  146. return list(data)
  147. elif data:
  148. return [data]
  149. else:
  150. return []
  151. class DictProperty(object):
  152. """Property that maps to a key in a local dict-like attribute."""
  153. def __init__(self, attr, key=None, read_only=False):
  154. self.attr, self.key, self.read_only = attr, key, read_only
  155. def __call__(self, func):
  156. functools.update_wrapper(self, func, updated=[])
  157. self.getter, self.key = func, self.key or func.__name__
  158. return self
  159. def __get__(self, obj, cls):
  160. if obj is None:
  161. return self
  162. key, storage = self.key, getattr(obj, self.attr)
  163. if key not in storage:
  164. storage[key] = self.getter(obj)
  165. return storage[key]
  166. def __set__(self, obj, value):
  167. if self.read_only:
  168. raise AttributeError("Read-Only property.")
  169. getattr(obj, self.attr)[self.key] = value
  170. def __delete__(self, obj):
  171. if self.read_only:
  172. raise AttributeError("Read-Only property.")
  173. del getattr(obj, self.attr)[self.key]
  174. class cached_property(object):
  175. """A property that is only computed once per instance and then replaces
  176. itself with an ordinary attribute. Deleting the attribute resets the
  177. property."""
  178. def __init__(self, func):
  179. self.__doc__ = getattr(func, "__doc__")
  180. self.func = func
  181. def __get__(self, obj, cls):
  182. if obj is None:
  183. return self
  184. value = obj.__dict__[self.func.__name__] = self.func(obj)
  185. return value
  186. class lazy_attribute(object):
  187. """A property that caches itself to the class object."""
  188. def __init__(self, func):
  189. functools.update_wrapper(self, func, updated=[])
  190. self.getter = func
  191. def __get__(self, obj, cls):
  192. value = self.getter(cls)
  193. setattr(cls, self.__name__, value)
  194. return value
  195. ###############################################################################
  196. # Exceptions and Events ########################################################
  197. ###############################################################################
  198. class BottleException(Exception):
  199. """A base class for exceptions used by bottle."""
  200. pass
  201. ###############################################################################
  202. # Routing ######################################################################
  203. ###############################################################################
  204. class RouteError(BottleException):
  205. """This is a base class for all routing related exceptions"""
  206. class RouteReset(BottleException):
  207. """If raised by a plugin or request handler, the route is reset and all
  208. plugins are re-applied."""
  209. class RouterUnknownModeError(RouteError):
  210. pass
  211. class RouteSyntaxError(RouteError):
  212. """The route parser found something not supported by this router."""
  213. class RouteBuildError(RouteError):
  214. """The route could not be built."""
  215. def _re_flatten(p):
  216. """Turn all capturing groups in a regular expression pattern into
  217. non-capturing groups."""
  218. if "(" not in p:
  219. return p
  220. return re.sub(
  221. r"(\\*)(\(\?P<[^>]+>|\((?!\?))",
  222. lambda m: m.group(0) if len(m.group(1)) % 2 else m.group(1) + "(?:",
  223. p,
  224. )
  225. class Router(object):
  226. """A Router is an ordered collection of route->target pairs. It is used to
  227. efficiently match WSGI requests against a number of routes and return
  228. the first target that satisfies the request. The target may be anything,
  229. usually a string, ID or callable object. A route consists of a path-rule
  230. and a HTTP method.
  231. The path-rule is either a static path (e.g. `/contact`) or a dynamic
  232. path that contains wildcards (e.g. `/wiki/<page>`). The wildcard syntax
  233. and details on the matching order are described in docs:`routing`.
  234. """
  235. default_pattern = "[^/]+"
  236. default_filter = "re"
  237. #: The current CPython regexp implementation does not allow more
  238. #: than 99 matching groups per regular expression.
  239. _MAX_GROUPS_PER_PATTERN = 99
  240. def __init__(self, strict=False):
  241. self.rules = [] # All rules in order
  242. self._groups = {} # index of regexes to find them in dyna_routes
  243. self.builder = {} # Data structure for the url builder
  244. self.static = {} # Search structure for static routes
  245. self.dyna_routes = {}
  246. self.dyna_regexes = {} # Search structure for dynamic routes
  247. #: If true, static routes are no longer checked first.
  248. self.strict_order = strict
  249. self.filters = {
  250. "re": lambda conf: (_re_flatten(conf or self.default_pattern), None, None),
  251. "int": lambda conf: (r"-?\d+", int, lambda x: str(int(x))),
  252. "float": lambda conf: (r"-?[\d.]+", float, lambda x: str(float(x))),
  253. "path": lambda conf: (r".+?", None, None),
  254. }
  255. def add_filter(self, name, func):
  256. """Add a filter. The provided function is called with the configuration
  257. string as parameter and must return a (regexp, to_python, to_url) tuple.
  258. The first element is a string, the last two are callables or None."""
  259. self.filters[name] = func
  260. rule_syntax = re.compile(
  261. "(\\\\*)"
  262. "(?:(?::([a-zA-Z_][a-zA-Z_0-9]*)?()(?:#(.*?)#)?)"
  263. "|(?:<([a-zA-Z_][a-zA-Z_0-9]*)?(?::([a-zA-Z_]*)"
  264. "(?::((?:\\\\.|[^\\\\>])+)?)?)?>))"
  265. )
  266. def _itertokens(self, rule):
  267. offset, prefix = 0, ""
  268. for match in self.rule_syntax.finditer(rule):
  269. prefix += rule[offset : match.start()]
  270. g = match.groups()
  271. if len(g[0]) % 2: # Escaped wildcard
  272. prefix += match.group(0)[len(g[0]) :]
  273. offset = match.end()
  274. continue
  275. if prefix:
  276. yield prefix, None, None
  277. name, filtr, conf = g[4:7] if g[2] is None else g[1:4]
  278. yield name, filtr or "default", conf or None
  279. offset, prefix = match.end(), ""
  280. if offset <= len(rule) or prefix:
  281. yield prefix + rule[offset:], None, None
  282. def add(self, rule, method, target, name=None):
  283. """Add a new rule or replace the target for an existing rule."""
  284. anons = 0 # Number of anonymous wildcards found
  285. keys = [] # Names of keys
  286. pattern = "" # Regular expression pattern with named groups
  287. filters = [] # Lists of wildcard input filters
  288. builder = [] # Data structure for the URL builder
  289. is_static = True
  290. for key, mode, conf in self._itertokens(rule):
  291. if mode:
  292. is_static = False
  293. if mode == "default":
  294. mode = self.default_filter
  295. mask, in_filter, out_filter = self.filters[mode](conf)
  296. if not key:
  297. pattern += "(?:%s)" % mask
  298. key = "anon%d" % anons
  299. anons += 1
  300. else:
  301. pattern += "(?P<%s>%s)" % (key, mask)
  302. keys.append(key)
  303. if in_filter:
  304. filters.append((key, in_filter))
  305. builder.append((key, out_filter or str))
  306. elif key:
  307. pattern += re.escape(key)
  308. builder.append((None, key))
  309. self.builder[rule] = builder
  310. if name:
  311. self.builder[name] = builder
  312. if is_static and not self.strict_order:
  313. self.static.setdefault(method, {})
  314. self.static[method][self.build(rule)] = (target, None)
  315. return
  316. try:
  317. re_pattern = re.compile("^(%s)$" % pattern)
  318. re_match = re_pattern.match
  319. except re.error:
  320. raise RouteSyntaxError("Could not add Route: %s (%s)" % (rule, _e()))
  321. if filters:
  322. def getargs(path):
  323. url_args = re_match(path).groupdict()
  324. for name, wildcard_filter in filters:
  325. try:
  326. url_args[name] = wildcard_filter(url_args[name])
  327. except ValueError:
  328. raise HTTPError(400, "Path has wrong format.")
  329. return url_args
  330. elif re_pattern.groupindex:
  331. def getargs(path):
  332. return re_match(path).groupdict()
  333. else:
  334. getargs = None
  335. flatpat = _re_flatten(pattern)
  336. whole_rule = (rule, flatpat, target, getargs)
  337. if (flatpat, method) in self._groups:
  338. if DEBUG:
  339. msg = "Route <%s %s> overwrites a previously defined route"
  340. warnings.warn(msg % (method, rule), RuntimeWarning)
  341. self.dyna_routes[method][self._groups[flatpat, method]] = whole_rule
  342. else:
  343. self.dyna_routes.setdefault(method, []).append(whole_rule)
  344. self._groups[flatpat, method] = len(self.dyna_routes[method]) - 1
  345. self._compile(method)
  346. def _compile(self, method):
  347. all_rules = self.dyna_routes[method]
  348. comborules = self.dyna_regexes[method] = []
  349. maxgroups = self._MAX_GROUPS_PER_PATTERN
  350. for x in range(0, len(all_rules), maxgroups):
  351. some = all_rules[x : x + maxgroups]
  352. combined = (flatpat for (_, flatpat, _, _) in some)
  353. combined = "|".join("(^%s$)" % flatpat for flatpat in combined)
  354. combined = re.compile(combined).match
  355. rules = [(target, getargs) for (_, _, target, getargs) in some]
  356. comborules.append((combined, rules))
  357. def build(self, _name, *anons, **query):
  358. """Build an URL by filling the wildcards in a rule."""
  359. builder = self.builder.get(_name)
  360. if not builder:
  361. raise RouteBuildError("No route with that name.", _name)
  362. try:
  363. for i, value in enumerate(anons):
  364. query["anon%d" % i] = value
  365. url = "".join([f(query.pop(n)) if n else f for (n, f) in builder])
  366. return url if not query else url + "?" + urlencode(query)
  367. except KeyError:
  368. raise RouteBuildError("Missing URL argument: %r" % _e().args[0])
  369. def match(self, environ):
  370. """Return a (target, url_agrs) tuple or raise HTTPError(400/404/405)."""
  371. verb = environ["REQUEST_METHOD"].upper()
  372. path = environ["PATH_INFO"] or "/"
  373. target = None
  374. if verb == "HEAD":
  375. methods = ["PROXY", verb, "GET", "ANY"]
  376. else:
  377. methods = ["PROXY", verb, "ANY"]
  378. for method in methods:
  379. if method in self.static and path in self.static[method]:
  380. target, getargs = self.static[method][path]
  381. return target, getargs(path) if getargs else {}
  382. elif method in self.dyna_regexes:
  383. for combined, rules in self.dyna_regexes[method]:
  384. match = combined(path)
  385. if match:
  386. target, getargs = rules[match.lastindex - 1]
  387. return target, getargs(path) if getargs else {}
  388. # No matching route found. Collect alternative methods for 405 response
  389. allowed = set([])
  390. nocheck = set(methods)
  391. for method in set(self.static) - nocheck:
  392. if path in self.static[method]:
  393. allowed.add(method)
  394. for method in set(self.dyna_regexes) - allowed - nocheck:
  395. for combined, rules in self.dyna_regexes[method]:
  396. match = combined(path)
  397. if match:
  398. allowed.add(method)
  399. if allowed:
  400. allow_header = ",".join(sorted(allowed))
  401. raise HTTPError(405, "Method not allowed.", Allow=allow_header)
  402. # No matching route and no alternative method found. We give up
  403. raise HTTPError(404, "Not found: " + repr(path))
  404. class Route(object):
  405. """This class wraps a route callback along with route specific metadata and
  406. configuration and applies Plugins on demand. It is also responsible for
  407. turing an URL path rule into a regular expression usable by the Router.
  408. """
  409. def __init__(
  410. self,
  411. app,
  412. rule,
  413. method,
  414. callback,
  415. name=None,
  416. plugins=None,
  417. skiplist=None,
  418. **config
  419. ):
  420. #: The application this route is installed to.
  421. self.app = app
  422. #: The path-rule string (e.g. ``/wiki/:page``).
  423. self.rule = rule
  424. #: The HTTP method as a string (e.g. ``GET``).
  425. self.method = method
  426. #: The original callback with no plugins applied. Useful for introspection.
  427. self.callback = callback
  428. #: The name of the route (if specified) or ``None``.
  429. self.name = name or None
  430. #: A list of route-specific plugins (see :meth:`Bottle.route`).
  431. self.plugins = plugins or []
  432. #: A list of plugins to not apply to this route (see :meth:`Bottle.route`).
  433. self.skiplist = skiplist or []
  434. #: Additional keyword arguments passed to the :meth:`Bottle.route`
  435. #: decorator are stored in this dictionary. Used for route-specific
  436. #: plugin configuration and meta-data.
  437. self.config = ConfigDict().load_dict(config, make_namespaces=True)
  438. def __call__(self, *a, **ka):
  439. depr(
  440. "Some APIs changed to return Route() instances instead of"
  441. " callables. Make sure to use the Route.call method and not to"
  442. " call Route instances directly."
  443. ) # 0.12
  444. return self.call(*a, **ka)
  445. @cached_property
  446. def call(self):
  447. """The route callback with all plugins applied. This property is
  448. created on demand and then cached to speed up subsequent requests."""
  449. return self._make_callback()
  450. def reset(self):
  451. """Forget any cached values. The next time :attr:`call` is accessed,
  452. all plugins are re-applied."""
  453. self.__dict__.pop("call", None)
  454. def prepare(self):
  455. """Do all on-demand work immediately (useful for debugging)."""
  456. self.call
  457. @property
  458. def _context(self):
  459. depr("Switch to Plugin API v2 and access the Route object directly.") # 0.12
  460. return dict(
  461. rule=self.rule,
  462. method=self.method,
  463. callback=self.callback,
  464. name=self.name,
  465. app=self.app,
  466. config=self.config,
  467. apply=self.plugins,
  468. skip=self.skiplist,
  469. )
  470. def all_plugins(self):
  471. """Yield all Plugins affecting this route."""
  472. unique = set()
  473. for p in reversed(self.app.plugins + self.plugins):
  474. if True in self.skiplist:
  475. break
  476. name = getattr(p, "name", False)
  477. if name and (name in self.skiplist or name in unique):
  478. continue
  479. if p in self.skiplist or type(p) in self.skiplist:
  480. continue
  481. if name:
  482. unique.add(name)
  483. yield p
  484. def _make_callback(self):
  485. callback = self.callback
  486. for plugin in self.all_plugins():
  487. try:
  488. if hasattr(plugin, "apply"):
  489. api = getattr(plugin, "api", 1)
  490. context = self if api > 1 else self._context
  491. callback = plugin.apply(callback, context)
  492. else:
  493. callback = plugin(callback)
  494. except RouteReset: # Try again with changed configuration.
  495. return self._make_callback()
  496. if not callback is self.callback:
  497. update_wrapper(callback, self.callback)
  498. return callback
  499. def get_undecorated_callback(self):
  500. """Return the callback. If the callback is a decorated function, try to
  501. recover the original function."""
  502. func = self.callback
  503. func = getattr(func, "__func__" if py3k else "im_func", func)
  504. closure_attr = "__closure__" if py3k else "func_closure"
  505. while hasattr(func, closure_attr) and getattr(func, closure_attr):
  506. func = getattr(func, closure_attr)[0].cell_contents
  507. return func
  508. def get_callback_args(self):
  509. """Return a list of argument names the callback (most likely) accepts
  510. as keyword arguments. If the callback is a decorated function, try
  511. to recover the original function before inspection."""
  512. return getargspec(self.get_undecorated_callback())[0]
  513. def get_config(self, key, default=None):
  514. """Lookup a config field and return its value, first checking the
  515. route.config, then route.app.config."""
  516. for conf in (self.config, self.app.config):
  517. if key in conf:
  518. return conf[key]
  519. return default
  520. def __repr__(self):
  521. cb = self.get_undecorated_callback()
  522. return "<%s %r %r>" % (self.method, self.rule, cb)
  523. ###############################################################################
  524. # Application Object ###########################################################
  525. ###############################################################################
  526. class Bottle(object):
  527. """Each Bottle object represents a single, distinct web application and
  528. consists of routes, callbacks, plugins, resources and configuration.
  529. Instances are callable WSGI applications.
  530. :param catchall: If true (default), handle all exceptions. Turn off to
  531. let debugging middleware handle exceptions.
  532. """
  533. def __init__(self, catchall=True, autojson=True):
  534. #: A :class:`ConfigDict` for app specific configuration.
  535. self.config = ConfigDict()
  536. self.config._on_change = functools.partial(self.trigger_hook, "config")
  537. self.config.meta_set("autojson", "validate", bool)
  538. self.config.meta_set("catchall", "validate", bool)
  539. self.config["catchall"] = catchall
  540. self.config["autojson"] = autojson
  541. #: A :class:`ResourceManager` for application files
  542. self.resources = ResourceManager()
  543. self.routes = [] # List of installed :class:`Route` instances.
  544. self.router = Router() # Maps requests to :class:`Route` instances.
  545. self.error_handler = {}
  546. # Core plugins
  547. self.plugins = [] # List of installed plugins.
  548. if self.config["autojson"]:
  549. self.install(JSONPlugin())
  550. self.install(TemplatePlugin())
  551. #: If true, most exceptions are caught and returned as :exc:`HTTPError`
  552. catchall = DictProperty("config", "catchall")
  553. __hook_names = "before_request", "after_request", "app_reset", "config"
  554. __hook_reversed = "after_request"
  555. @cached_property
  556. def _hooks(self):
  557. return dict((name, []) for name in self.__hook_names)
  558. def add_hook(self, name, func):
  559. """Attach a callback to a hook. Three hooks are currently implemented:
  560. before_request
  561. Executed once before each request. The request context is
  562. available, but no routing has happened yet.
  563. after_request
  564. Executed once after each request regardless of its outcome.
  565. app_reset
  566. Called whenever :meth:`Bottle.reset` is called.
  567. """
  568. if name in self.__hook_reversed:
  569. self._hooks[name].insert(0, func)
  570. else:
  571. self._hooks[name].append(func)
  572. def remove_hook(self, name, func):
  573. """Remove a callback from a hook."""
  574. if name in self._hooks and func in self._hooks[name]:
  575. self._hooks[name].remove(func)
  576. return True
  577. def trigger_hook(self, __name, *args, **kwargs):
  578. """Trigger a hook and return a list of results."""
  579. return [hook(*args, **kwargs) for hook in self._hooks[__name][:]]
  580. def hook(self, name):
  581. """Return a decorator that attaches a callback to a hook. See
  582. :meth:`add_hook` for details."""
  583. def decorator(func):
  584. self.add_hook(name, func)
  585. return func
  586. return decorator
  587. def mount(self, prefix, app, **options):
  588. """Mount an application (:class:`Bottle` or plain WSGI) to a specific
  589. URL prefix. Example::
  590. root_app.mount('/admin/', admin_app)
  591. :param prefix: path prefix or `mount-point`. If it ends in a slash,
  592. that slash is mandatory.
  593. :param app: an instance of :class:`Bottle` or a WSGI application.
  594. All other parameters are passed to the underlying :meth:`route` call.
  595. """
  596. if isinstance(app, basestring):
  597. depr("Parameter order of Bottle.mount() changed.", True) # 0.10
  598. segments = [p for p in prefix.split("/") if p]
  599. if not segments:
  600. raise ValueError("Empty path prefix.")
  601. path_depth = len(segments)
  602. def mountpoint_wrapper():
  603. try:
  604. request.path_shift(path_depth)
  605. rs = HTTPResponse([])
  606. def start_response(status, headerlist, exc_info=None):
  607. if exc_info:
  608. try:
  609. _raise(*exc_info)
  610. finally:
  611. exc_info = None
  612. rs.status = status
  613. for name, value in headerlist:
  614. rs.add_header(name, value)
  615. return rs.body.append
  616. body = app(request.environ, start_response)
  617. if body and rs.body:
  618. body = itertools.chain(rs.body, body)
  619. rs.body = body or rs.body
  620. return rs
  621. finally:
  622. request.path_shift(-path_depth)
  623. options.setdefault("skip", True)
  624. options.setdefault("method", "PROXY")
  625. options.setdefault("mountpoint", {"prefix": prefix, "target": app})
  626. options["callback"] = mountpoint_wrapper
  627. self.route("/%s/<:re:.*>" % "/".join(segments), **options)
  628. if not prefix.endswith("/"):
  629. self.route("/" + "/".join(segments), **options)
  630. def merge(self, routes):
  631. """Merge the routes of another :class:`Bottle` application or a list of
  632. :class:`Route` objects into this application. The routes keep their
  633. 'owner', meaning that the :data:`Route.app` attribute is not
  634. changed."""
  635. if isinstance(routes, Bottle):
  636. routes = routes.routes
  637. for route in routes:
  638. self.add_route(route)
  639. def install(self, plugin):
  640. """Add a plugin to the list of plugins and prepare it for being
  641. applied to all routes of this application. A plugin may be a simple
  642. decorator or an object that implements the :class:`Plugin` API.
  643. """
  644. if hasattr(plugin, "setup"):
  645. plugin.setup(self)
  646. if not callable(plugin) and not hasattr(plugin, "apply"):
  647. raise TypeError("Plugins must be callable or implement .apply()")
  648. self.plugins.append(plugin)
  649. self.reset()
  650. return plugin
  651. def uninstall(self, plugin):
  652. """Uninstall plugins. Pass an instance to remove a specific plugin, a type
  653. object to remove all plugins that match that type, a string to remove
  654. all plugins with a matching ``name`` attribute or ``True`` to remove all
  655. plugins. Return the list of removed plugins."""
  656. removed, remove = [], plugin
  657. for i, plugin in list(enumerate(self.plugins))[::-1]:
  658. if (
  659. remove is True
  660. or remove is plugin
  661. or remove is type(plugin)
  662. or getattr(plugin, "name", True) == remove
  663. ):
  664. removed.append(plugin)
  665. del self.plugins[i]
  666. if hasattr(plugin, "close"):
  667. plugin.close()
  668. if removed:
  669. self.reset()
  670. return removed
  671. def reset(self, route=None):
  672. """Reset all routes (force plugins to be re-applied) and clear all
  673. caches. If an ID or route object is given, only that specific route
  674. is affected."""
  675. if route is None:
  676. routes = self.routes
  677. elif isinstance(route, Route):
  678. routes = [route]
  679. else:
  680. routes = [self.routes[route]]
  681. for route in routes:
  682. route.reset()
  683. if DEBUG:
  684. for route in routes:
  685. route.prepare()
  686. self.trigger_hook("app_reset")
  687. def close(self):
  688. """Close the application and all installed plugins."""
  689. for plugin in self.plugins:
  690. if hasattr(plugin, "close"):
  691. plugin.close()
  692. self.stopped = True
  693. def run(self, **kwargs):
  694. """Calls :func:`run` with the same parameters."""
  695. run(self, **kwargs)
  696. def match(self, environ):
  697. """Search for a matching route and return a (:class:`Route` , urlargs)
  698. tuple. The second value is a dictionary with parameters extracted
  699. from the URL. Raise :exc:`HTTPError` (404/405) on a non-match."""
  700. return self.router.match(environ)
  701. def get_url(self, routename, **kargs):
  702. """Return a string that matches a named route"""
  703. scriptname = request.environ.get("SCRIPT_NAME", "").strip("/") + "/"
  704. location = self.router.build(routename, **kargs).lstrip("/")
  705. return urljoin(urljoin("/", scriptname), location)
  706. def add_route(self, route):
  707. """Add a route object, but do not change the :data:`Route.app`
  708. attribute."""
  709. self.routes.append(route)
  710. self.router.add(route.rule, route.method, route, name=route.name)
  711. if DEBUG:
  712. route.prepare()
  713. def route(
  714. self,
  715. path=None,
  716. method="GET",
  717. callback=None,
  718. name=None,
  719. apply=None,
  720. skip=None,
  721. **config
  722. ):
  723. """A decorator to bind a function to a request URL. Example::
  724. @app.route('/hello/:name')
  725. def hello(name):
  726. return 'Hello %s' % name
  727. The ``:name`` part is a wildcard. See :class:`Router` for syntax
  728. details.
  729. :param path: Request path or a list of paths to listen to. If no
  730. path is specified, it is automatically generated from the
  731. signature of the function.
  732. :param method: HTTP method (`GET`, `POST`, `PUT`, ...) or a list of
  733. methods to listen to. (default: `GET`)
  734. :param callback: An optional shortcut to avoid the decorator
  735. syntax. ``route(..., callback=func)`` equals ``route(...)(func)``
  736. :param name: The name for this route. (default: None)
  737. :param apply: A decorator or plugin or a list of plugins. These are
  738. applied to the route callback in addition to installed plugins.
  739. :param skip: A list of plugins, plugin classes or names. Matching
  740. plugins are not installed to this route. ``True`` skips all.
  741. Any additional keyword arguments are stored as route-specific
  742. configuration and passed to plugins (see :meth:`Plugin.apply`).
  743. """
  744. if callable(path):
  745. path, callback = None, path
  746. plugins = makelist(apply)
  747. skiplist = makelist(skip)
  748. def decorator(callback):
  749. # TODO: Documentation and tests
  750. if isinstance(callback, basestring):
  751. callback = load(callback)
  752. for rule in makelist(path) or yieldroutes(callback):
  753. for verb in makelist(method):
  754. verb = verb.upper()
  755. route = Route(
  756. self,
  757. rule,
  758. verb,
  759. callback,
  760. name=name,
  761. plugins=plugins,
  762. skiplist=skiplist,
  763. **config
  764. )
  765. self.add_route(route)
  766. return callback
  767. return decorator(callback) if callback else decorator
  768. def get(self, path=None, method="GET", **options):
  769. """Equals :meth:`route`."""
  770. return self.route(path, method, **options)
  771. def post(self, path=None, method="POST", **options):
  772. """Equals :meth:`route` with a ``POST`` method parameter."""
  773. return self.route(path, method, **options)
  774. def put(self, path=None, method="PUT", **options):
  775. """Equals :meth:`route` with a ``PUT`` method parameter."""
  776. return self.route(path, method, **options)
  777. def delete(self, path=None, method="DELETE", **options):
  778. """Equals :meth:`route` with a ``DELETE`` method parameter."""
  779. return self.route(path, method, **options)
  780. def error(self, code=500):
  781. """Decorator: Register an output handler for a HTTP error code"""
  782. def wrapper(handler):
  783. self.error_handler[int(code)] = handler
  784. return handler
  785. return wrapper
  786. def default_error_handler(self, res):
  787. return tob(template(ERROR_PAGE_TEMPLATE, e=res))
  788. def _handle(self, environ):
  789. try:
  790. environ["bottle.app"] = self
  791. request.bind(environ)
  792. response.bind()
  793. path = environ["bottle.raw_path"] = environ["PATH_INFO"]
  794. if py3k:
  795. try:
  796. environ["PATH_INFO"] = path.encode("latin1").decode("utf8")
  797. except UnicodeError:
  798. return HTTPError(400, "Invalid path string. Expected UTF-8")
  799. try:
  800. self.trigger_hook("before_request")
  801. route, args = self.router.match(environ)
  802. environ["route.handle"] = route
  803. environ["bottle.route"] = route
  804. environ["route.url_args"] = args
  805. return route.call(**args)
  806. finally:
  807. self.trigger_hook("after_request")
  808. except HTTPResponse:
  809. return _e()
  810. except RouteReset:
  811. route.reset()
  812. return self._handle(environ)
  813. except (KeyboardInterrupt, SystemExit, MemoryError):
  814. raise
  815. except Exception:
  816. if not self.catchall:
  817. raise
  818. stacktrace = format_exc()
  819. environ["wsgi.errors"].write(stacktrace)
  820. return HTTPError(500, "Internal Server Error", _e(), stacktrace)
  821. def _cast(self, out, peek=None):
  822. """Try to convert the parameter into something WSGI compatible and set
  823. correct HTTP headers when possible.
  824. Support: False, str, unicode, dict, HTTPResponse, HTTPError, file-like,
  825. iterable of strings and iterable of unicodes
  826. """
  827. # Empty output is done here
  828. if not out:
  829. if "Content-Length" not in response:
  830. response["Content-Length"] = 0
  831. return []
  832. # Join lists of byte or unicode strings. Mixed lists are NOT supported
  833. if isinstance(out, (tuple, list)) and isinstance(out[0], (bytes, unicode)):
  834. out = out[0][0:0].join(out) # b'abc'[0:0] -> b''
  835. # Encode unicode strings
  836. if isinstance(out, unicode):
  837. out = out.encode(response.charset)
  838. # Byte Strings are just returned
  839. if isinstance(out, bytes):
  840. if "Content-Length" not in response:
  841. response["Content-Length"] = len(out)
  842. return [out]
  843. # HTTPError or HTTPException (recursive, because they may wrap anything)
  844. # TODO: Handle these explicitly in handle() or make them iterable.
  845. if isinstance(out, HTTPError):
  846. out.apply(response)
  847. out = self.error_handler.get(out.status_code, self.default_error_handler)(
  848. out
  849. )
  850. return self._cast(out)
  851. if isinstance(out, HTTPResponse):
  852. out.apply(response)
  853. return self._cast(out.body)
  854. # File-like objects.
  855. if hasattr(out, "read"):
  856. if "wsgi.file_wrapper" in request.environ:
  857. return request.environ["wsgi.file_wrapper"](out)
  858. elif hasattr(out, "close") or not hasattr(out, "__iter__"):
  859. return WSGIFileWrapper(out)
  860. # Handle Iterables. We peek into them to detect their inner type.
  861. try:
  862. iout = iter(out)
  863. first = next(iout)
  864. while not first:
  865. first = next(iout)
  866. except StopIteration:
  867. return self._cast("")
  868. except HTTPResponse:
  869. first = _e()
  870. except (KeyboardInterrupt, SystemExit, MemoryError):
  871. raise
  872. except Exception:
  873. if not self.catchall:
  874. raise
  875. first = HTTPError(500, "Unhandled exception", _e(), format_exc())
  876. # These are the inner types allowed in iterator or generator objects.
  877. if isinstance(first, HTTPResponse):
  878. return self._cast(first)
  879. elif isinstance(first, bytes):
  880. new_iter = itertools.chain([first], iout)
  881. elif isinstance(first, unicode):
  882. encoder = lambda x: x.encode(response.charset)
  883. new_iter = imap(encoder, itertools.chain([first], iout))
  884. else:
  885. msg = "Unsupported response type: %s" % type(first)
  886. return self._cast(HTTPError(500, msg))
  887. if hasattr(out, "close"):
  888. new_iter = _closeiter(new_iter, out.close)
  889. return new_iter
  890. def wsgi(self, environ, start_response):
  891. """The bottle WSGI-interface."""
  892. try:
  893. out = self._cast(self._handle(environ))
  894. # rfc2616 section 4.3
  895. if (
  896. response._status_code in (100, 101, 204, 304)
  897. or environ["REQUEST_METHOD"] == "HEAD"
  898. ):
  899. if hasattr(out, "close"):
  900. out.close()
  901. out = []
  902. start_response(response._status_line, response.headerlist)
  903. return out
  904. except (KeyboardInterrupt, SystemExit, MemoryError):
  905. raise
  906. except Exception:
  907. if not self.catchall:
  908. raise
  909. err = "<h1>Critical error while processing request: %s</h1>" % html_escape(
  910. environ.get("PATH_INFO", "/")
  911. )
  912. if DEBUG:
  913. err += (
  914. "<h2>Error:</h2>\n<pre>\n%s\n</pre>\n"
  915. "<h2>Traceback:</h2>\n<pre>\n%s\n</pre>\n"
  916. % (html_escape(repr(_e())), html_escape(format_exc()))
  917. )
  918. environ["wsgi.errors"].write(err)
  919. headers = [("Content-Type", "text/html; charset=UTF-8")]
  920. start_response("500 INTERNAL SERVER ERROR", headers, sys.exc_info())
  921. return [tob(err)]
  922. def __call__(self, environ, start_response):
  923. """Each instance of :class:'Bottle' is a WSGI application."""
  924. return self.wsgi(environ, start_response)
  925. ###############################################################################
  926. # HTTP and WSGI Tools ##########################################################
  927. ###############################################################################
  928. class BaseRequest(object):
  929. """A wrapper for WSGI environment dictionaries that adds a lot of
  930. convenient access methods and properties. Most of them are read-only.
  931. Adding new attributes to a request actually adds them to the environ
  932. dictionary (as 'bottle.request.ext.<name>'). This is the recommended
  933. way to store and access request-specific data.
  934. """
  935. __slots__ = "environ"
  936. #: Maximum size of memory buffer for :attr:`body` in bytes.
  937. MEMFILE_MAX = 102400
  938. def __init__(self, environ=None):
  939. """Wrap a WSGI environ dictionary."""
  940. #: The wrapped WSGI environ dictionary. This is the only real attribute.
  941. #: All other attributes actually are read-only properties.
  942. self.environ = {} if environ is None else environ
  943. self.environ["bottle.request"] = self
  944. @DictProperty("environ", "bottle.app", read_only=True)
  945. def app(self):
  946. """Bottle application handling this request."""
  947. raise RuntimeError("This request is not connected to an application.")
  948. @DictProperty("environ", "bottle.route", read_only=True)
  949. def route(self):
  950. """The bottle :class:`Route` object that matches this request."""
  951. raise RuntimeError("This request is not connected to a route.")
  952. @DictProperty("environ", "route.url_args", read_only=True)
  953. def url_args(self):
  954. """The arguments extracted from the URL."""
  955. raise RuntimeError("This request is not connected to a route.")
  956. @property
  957. def path(self):
  958. """The value of ``PATH_INFO`` with exactly one prefixed slash (to fix
  959. broken clients and avoid the "empty path" edge case)."""
  960. return "/" + self.environ.get("PATH_INFO", "").lstrip("/")
  961. @property
  962. def method(self):
  963. """The ``REQUEST_METHOD`` value as an uppercase string."""
  964. return self.environ.get("REQUEST_METHOD", "GET").upper()
  965. @DictProperty("environ", "bottle.request.headers", read_only=True)
  966. def headers(self):
  967. """A :class:`WSGIHeaderDict` that provides case-insensitive access to
  968. HTTP request headers."""
  969. return WSGIHeaderDict(self.environ)
  970. def get_header(self, name, default=None):
  971. """Return the value of a request header, or a given default value."""
  972. return self.headers.get(name, default)
  973. @DictProperty("environ", "bottle.request.cookies", read_only=True)
  974. def cookies(self):
  975. """Cookies parsed into a :class:`FormsDict`. Signed cookies are NOT
  976. decoded. Use :meth:`get_cookie` if you expect signed cookies."""
  977. cookies = SimpleCookie(self.environ.get("HTTP_COOKIE", "")).values()
  978. return FormsDict((c.key, c.value) for c in cookies)
  979. def get_cookie(self, key, default=None, secret=None):
  980. """Return the content of a cookie. To read a `Signed Cookie`, the
  981. `secret` must match the one used to create the cookie (see
  982. :meth:`BaseResponse.set_cookie`). If anything goes wrong (missing
  983. cookie or wrong signature), return a default value."""
  984. value = self.cookies.get(key)
  985. if secret and value:
  986. dec = cookie_decode(value, secret) # (key, value) tuple or None
  987. return dec[1] if dec and dec[0] == key else default
  988. return value or default
  989. @DictProperty("environ", "bottle.request.query", read_only=True)
  990. def query(self):
  991. """The :attr:`query_string` parsed into a :class:`FormsDict`. These
  992. values are sometimes called "URL arguments" or "GET parameters", but
  993. not to be confused with "URL wildcards" as they are provided by the
  994. :class:`Router`."""
  995. get = self.environ["bottle.get"] = FormsDict()
  996. pairs = _parse_qsl(self.environ.get("QUERY_STRING", ""))
  997. for key, value in pairs:
  998. get[key] = value
  999. return get
  1000. @DictProperty("environ", "bottle.request.forms", read_only=True)
  1001. def forms(self):
  1002. """Form values parsed from an `url-encoded` or `multipart/form-data`
  1003. encoded POST or PUT request body. The result is returned as a
  1004. :class:`FormsDict`. All keys and values are strings. File uploads
  1005. are stored separately in :attr:`files`."""
  1006. forms = FormsDict()
  1007. forms.recode_unicode = self.POST.recode_unicode
  1008. for name, item in self.POST.allitems():
  1009. if not isinstance(item, FileUpload):
  1010. forms[name] = item
  1011. return forms
  1012. @DictProperty("environ", "bottle.request.params", read_only=True)
  1013. def params(self):
  1014. """A :class:`FormsDict` with the combined values of :attr:`query` and
  1015. :attr:`forms`. File uploads are stored in :attr:`files`."""
  1016. params = FormsDict()
  1017. for key, value in self.query.allitems():
  1018. params[key] = value
  1019. for key, value in self.forms.allitems():
  1020. params[key] = value
  1021. return params
  1022. @DictProperty("environ", "bottle.request.files", read_only=True)
  1023. def files(self):
  1024. """File uploads parsed from `multipart/form-data` encoded POST or PUT
  1025. request body. The values are instances of :class:`FileUpload`.
  1026. """
  1027. files = FormsDict()
  1028. files.recode_unicode = self.POST.recode_unicode
  1029. for name, item in self.POST.allitems():
  1030. if isinstance(item, FileUpload):
  1031. files[name] = item
  1032. return files
  1033. @DictProperty("environ", "bottle.request.json", read_only=True)
  1034. def json(self):
  1035. """If the ``Content-Type`` header is ``application/json``, this
  1036. property holds the parsed content of the request body. Only requests
  1037. smaller than :attr:`MEMFILE_MAX` are processed to avoid memory
  1038. exhaustion."""
  1039. ctype = self.environ.get("CONTENT_TYPE", "").lower().split(";")[0]
  1040. if ctype == "application/json":
  1041. b = self._get_body_string()
  1042. if not b:
  1043. return None
  1044. return json_loads(b)
  1045. return None
  1046. def _iter_body(self, read, bufsize):
  1047. maxread = max(0, self.content_length)
  1048. while maxread:
  1049. part = read(min(maxread, bufsize))
  1050. if not part:
  1051. break
  1052. yield part
  1053. maxread -= len(part)
  1054. def _iter_chunked(self, read, bufsize):
  1055. err = HTTPError(400, "Error while parsing chunked transfer body.")
  1056. rn, sem, bs = tob("\r\n"), tob(";"), tob("")
  1057. while True:
  1058. header = read(1)
  1059. while header[-2:] != rn:
  1060. c = read(1)
  1061. header += c
  1062. if not c:
  1063. raise err
  1064. if len(header) > bufsize:
  1065. raise err
  1066. size, _, _ = header.partition(sem)
  1067. try:
  1068. maxread = int(tonat(size.strip()), 16)
  1069. except ValueError:
  1070. raise err
  1071. if maxread == 0:
  1072. break
  1073. buff = bs
  1074. while maxread > 0:
  1075. if not buff:
  1076. buff = read(min(maxread, bufsize))
  1077. part, buff = buff[:maxread], buff[maxread:]
  1078. if not part:
  1079. raise err
  1080. yield part
  1081. maxread -= len(part)
  1082. if read(2) != rn:
  1083. raise err
  1084. @DictProperty("environ", "bottle.request.body", read_only=True)
  1085. def _body(self):
  1086. body_iter = self._iter_chunked if self.chunked else self._iter_body
  1087. read_func = self.environ["wsgi.input"].read
  1088. body, body_size, is_temp_file = BytesIO(), 0, False
  1089. for part in body_iter(read_func, self.MEMFILE_MAX):
  1090. body.write(part)
  1091. body_size += len(part)
  1092. if not is_temp_file and body_size > self.MEMFILE_MAX:
  1093. body, tmp = TemporaryFile(mode="w+b"), body
  1094. body.write(tmp.getvalue())
  1095. del tmp
  1096. is_temp_file = True
  1097. self.environ["wsgi.input"] = body
  1098. body.seek(0)
  1099. return body
  1100. def _get_body_string(self):
  1101. """read body until content-length or MEMFILE_MAX into a string. Raise
  1102. HTTPError(413) on requests that are to large."""
  1103. clen = self.content_length
  1104. if clen > self.MEMFILE_MAX:
  1105. raise HTTPError(413, "Request to large")
  1106. if clen < 0:
  1107. clen = self.MEMFILE_MAX + 1
  1108. data = self.body.read(clen)
  1109. if len(data) > self.MEMFILE_MAX: # Fail fast
  1110. raise HTTPError(413, "Request to large")
  1111. return data
  1112. @property
  1113. def body(self):
  1114. """The HTTP request body as a seek-able file-like object. Depending on
  1115. :attr:`MEMFILE_MAX`, this is either a temporary file or a
  1116. :class:`io.BytesIO` instance. Accessing this property for the first
  1117. time reads and replaces the ``wsgi.input`` environ variable.
  1118. Subsequent accesses just do a `seek(0)` on the file object."""
  1119. self._body.seek(0)
  1120. return self._body
  1121. @property
  1122. def chunked(self):
  1123. """True if Chunked transfer encoding was."""
  1124. return "chunked" in self.environ.get("HTTP_TRANSFER_ENCODING", "").lower()
  1125. #: An alias for :attr:`query`.
  1126. GET = query
  1127. @DictProperty("environ", "bottle.request.post", read_only=True)
  1128. def POST(self):
  1129. """The values of :attr:`forms` and :attr:`files` combined into a single
  1130. :class:`FormsDict`. Values are either strings (form values) or
  1131. instances of :class:`cgi.FieldStorage` (file uploads).
  1132. """
  1133. post = FormsDict()
  1134. # We default to application/x-www-form-urlencoded for everything that
  1135. # is not multipart and take the fast path (also: 3.1 workaround)
  1136. if not self.content_type.startswith("multipart/"):
  1137. pairs = _parse_qsl(tonat(self._get_body_string(), "latin1"))
  1138. for key, value in pairs:
  1139. post[key] = value
  1140. return post
  1141. safe_env = {"QUERY_STRING": ""} # Build a safe environment for cgi
  1142. for key in ("REQUEST_METHOD", "CONTENT_TYPE", "CONTENT_LENGTH"):
  1143. if key in self.environ:
  1144. safe_env[key] = self.environ[key]
  1145. args = dict(fp=self.body, environ=safe_env, keep_blank_values=True)
  1146. if py31:
  1147. args["fp"] = NCTextIOWrapper(args["fp"], encoding="utf8", newline="\n")
  1148. elif py3k:
  1149. args["encoding"] = "utf8"
  1150. post.recode_unicode = False
  1151. data = cgi.FieldStorage(**args)
  1152. self["_cgi.FieldStorage"] = data # http://bugs.python.org/issue18394#msg207958
  1153. data = data.list or []
  1154. for item in data:
  1155. if item.filename is None:
  1156. post[item.name] = item.value
  1157. else:
  1158. post[item.name] = FileUpload(
  1159. item.file, item.name, item.filename, item.headers
  1160. )
  1161. return post
  1162. @property
  1163. def url(self):
  1164. """The full request URI including hostname and scheme. If your app
  1165. lives behind a reverse proxy or load balancer and you get confusing
  1166. results, make sure that the ``X-Forwarded-Host`` header is set
  1167. correctly."""
  1168. return self.urlparts.geturl()
  1169. @DictProperty("environ", "bottle.request.urlparts", read_only=True)
  1170. def urlparts(self):
  1171. """The :attr:`url` string as an :class:`urlparse.SplitResult` tuple.
  1172. The tuple contains (scheme, host, path, query_string and fragment),
  1173. but the fragment is always empty because it is not visible to the
  1174. server."""
  1175. env = self.environ
  1176. http = env.get("HTTP_X_FORWARDED_PROTO") or env.get("wsgi.url_scheme", "http")
  1177. host = env.get("HTTP_X_FORWARDED_HOST") or env.get("HTTP_HOST")
  1178. if not host:
  1179. # HTTP 1.1 requires a Host-header. This is for HTTP/1.0 clients.
  1180. host = env.get("SERVER_NAME", "127.0.0.1")
  1181. port = env.get("SERVER_PORT")
  1182. if port and port != ("80" if http == "http" else "443"):
  1183. host += ":" + port
  1184. path = urlquote(self.fullpath)
  1185. return UrlSplitResult(http, host, path, env.get("QUERY_STRING"), "")
  1186. @property
  1187. def fullpath(self):
  1188. """Request path including :attr:`script_name` (if present)."""
  1189. return urljoin(self.script_name, self.path.lstrip("/"))
  1190. @property
  1191. def query_string(self):
  1192. """The raw :attr:`query` part of the URL (everything in between ``?``
  1193. and ``#``) as a string."""
  1194. return self.environ.get("QUERY_STRING", "")
  1195. @property
  1196. def script_name(self):
  1197. """The initial portion of the URL's `path` that was removed by a higher
  1198. level (server or routing middleware) before the application was
  1199. called. This script path is returned with leading and tailing
  1200. slashes."""
  1201. script_name = self.environ.get("SCRIPT_NAME", "").strip("/")
  1202. return "/" + script_name + "/" if script_name else "/"
  1203. def path_shift(self, shift=1):
  1204. """Shift path segments from :attr:`path` to :attr:`script_name` and
  1205. vice versa.
  1206. :param shift: The number of path segments to shift. May be negative
  1207. to change the shift direction. (default: 1)
  1208. """
  1209. script = self.environ.get("SCRIPT_NAME", "/")
  1210. self["SCRIPT_NAME"], self["PATH_INFO"] = path_shift(script, self.path, shift)
  1211. @property
  1212. def content_length(self):
  1213. """The request body length as an integer. The client is responsible to
  1214. set this header. Otherwise, the real length of the body is unknown
  1215. and -1 is returned. In this case, :attr:`body` will be empty."""
  1216. return int(self.environ.get("CONTENT_LENGTH") or -1)
  1217. @property
  1218. def content_type(self):
  1219. """The Content-Type header as a lowercase-string (default: empty)."""
  1220. return self.environ.get("CONTENT_TYPE", "").lower()
  1221. @property
  1222. def is_xhr(self):
  1223. """True if the request was triggered by a XMLHttpRequest. This only
  1224. works with JavaScript libraries that support the `X-Requested-With`
  1225. header (most of the popular libraries do)."""
  1226. requested_with = self.environ.get("HTTP_X_REQUESTED_WITH", "")
  1227. return requested_with.lower() == "xmlhttprequest"
  1228. @property
  1229. def is_ajax(self):
  1230. """Alias for :attr:`is_xhr`. "Ajax" is not the right term."""
  1231. return self.is_xhr
  1232. @property
  1233. def auth(self):
  1234. """HTTP authentication data as a (user, password) tuple. This
  1235. implementation currently supports basic (not digest) authentication
  1236. only. If the authentication happened at a higher level (e.g. in the
  1237. front web-server or a middleware), the password field is None, but
  1238. the user field is looked up from the ``REMOTE_USER`` environ
  1239. variable. On any errors, None is returned."""
  1240. basic = parse_auth(self.environ.get("HTTP_AUTHORIZATION", ""))
  1241. if basic:
  1242. return basic
  1243. ruser = self.environ.get("REMOTE_USER")
  1244. if ruser:
  1245. return (ruser, None)
  1246. return None
  1247. @property
  1248. def remote_route(self):
  1249. """A list of all IPs that were involved in this request, starting with
  1250. the client IP and followed by zero or more proxies. This does only
  1251. work if all proxies support the ```X-Forwarded-For`` header. Note
  1252. that this information can be forged by malicious clients."""
  1253. proxy = self.environ.get("HTTP_X_FORWARDED_FOR")
  1254. if proxy:
  1255. return [ip.strip() for ip in proxy.split(",")]
  1256. remote = self.environ.get("REMOTE_ADDR")
  1257. return [remote] if remote else []
  1258. @property
  1259. def remote_addr(self):
  1260. """The client IP as a string. Note that this information can be forged
  1261. by malicious clients."""
  1262. route = self.remote_route
  1263. return route[0] if route else None
  1264. def copy(self):
  1265. """Return a new :class:`Request` with a shallow :attr:`environ` copy."""
  1266. return Request(self.environ.copy())
  1267. def get(self, value, default=None):
  1268. return self.environ.get(value, default)
  1269. def __getitem__(self, key):
  1270. return self.environ[key]
  1271. def __delitem__(self, key):
  1272. self[key] = ""
  1273. del self.environ[key]
  1274. def __iter__(self):
  1275. return iter(self.environ)
  1276. def __len__(self):
  1277. return len(self.environ)
  1278. def keys(self):
  1279. return self.environ.keys()
  1280. def __setitem__(self, key, value):
  1281. """Change an environ value and clear all caches that depend on it."""
  1282. if self.environ.get("bottle.request.readonly"):
  1283. raise KeyError("The environ dictionary is read-only.")
  1284. self.environ[key] = value
  1285. todelete = ()
  1286. if key == "wsgi.input":
  1287. todelete = ("body", "forms", "files", "params", "post", "json")
  1288. elif key == "QUERY_STRING":
  1289. todelete = ("query", "params")
  1290. elif key.startswith("HTTP_"):
  1291. todelete = ("headers", "cookies")
  1292. for key in todelete:
  1293. self.environ.pop("bottle.request." + key, None)
  1294. def __repr__(self):
  1295. return "<%s: %s %s>" % (self.__class__.__name__, self.method, self.url)
  1296. def __getattr__(self, name):
  1297. """Search in self.environ for additional user defined attributes."""
  1298. try:
  1299. var = self.environ["bottle.request.ext.%s" % name]
  1300. return var.__get__(self) if hasattr(var, "__get__") else var
  1301. except KeyError:
  1302. raise AttributeError("Attribute %r not defined." % name)
  1303. def __setattr__(self, name, value):
  1304. if name == "environ":
  1305. return object.__setattr__(self, name, value)
  1306. self.environ["bottle.request.ext.%s" % name] = value
  1307. def _hkey(key):
  1308. if "\n" in key or "\r" in key or "\0" in key:
  1309. raise ValueError("Header names must not contain control characters: %r" % key)
  1310. return key.title().replace("_", "-")
  1311. def _hval(value):
  1312. value = tonat(value)
  1313. if "\n" in value or "\r" in value or "\0" in value:
  1314. raise ValueError("Header value must not contain control characters: %r" % value)
  1315. return value
  1316. class HeaderProperty(object):
  1317. def __init__(self, name, reader=None, writer=None, default=""):
  1318. self.name, self.default = name, default
  1319. self.reader, self.writer = reader, writer
  1320. self.__doc__ = "Current value of the %r header." % name.title()
  1321. def __get__(self, obj, cls):
  1322. if obj is None:
  1323. return self
  1324. value = obj.get_header(self.name, self.default)
  1325. return self.reader(value) if self.reader else value
  1326. def __set__(self, obj, value):
  1327. obj[self.name] = self.writer(value) if self.writer else value
  1328. def __delete__(self, obj):
  1329. del obj[self.name]
  1330. class BaseResponse(object):
  1331. """Storage class for a response body as well as headers and cookies.
  1332. This class does support dict-like case-insensitive item-access to
  1333. headers, but is NOT a dict. Most notably, iterating over a response
  1334. yields parts of the body and not the headers.
  1335. :param body: The response body as one of the supported types.
  1336. :param status: Either an HTTP status code (e.g. 200) or a status line
  1337. including the reason phrase (e.g. '200 OK').
  1338. :param headers: A dictionary or a list of name-value pairs.
  1339. Additional keyword arguments are added to the list of headers.
  1340. Underscores in the header name are replaced with dashes.
  1341. """
  1342. default_status = 200
  1343. default_content_type = "text/html; charset=UTF-8"
  1344. # Header blacklist for specific response codes
  1345. # (rfc2616 section 10.2.3 and 10.3.5)
  1346. bad_headers = {
  1347. 204: set(("Content-Type",)),
  1348. 304: set(
  1349. (
  1350. "Allow",
  1351. "Content-Encoding",
  1352. "Content-Language",
  1353. "Content-Length",
  1354. "Content-Range",
  1355. "Content-Type",
  1356. "Content-Md5",
  1357. "Last-Modified",
  1358. )
  1359. ),
  1360. }
  1361. def __init__(self, body="", status=None, headers=None, **more_headers):
  1362. self._cookies = None
  1363. self._headers = {}
  1364. self.body = body
  1365. self.status = status or self.default_status
  1366. if headers:
  1367. if isinstance(headers, dict):
  1368. headers = headers.items()
  1369. for name, value in headers:
  1370. self.add_header(name, value)
  1371. if more_headers:
  1372. for name, value in more_headers.items():
  1373. self.add_header(name, value)
  1374. def copy(self, cls=None):
  1375. """Returns a copy of self."""
  1376. cls = cls or BaseResponse
  1377. assert issubclass(cls, BaseResponse)
  1378. copy = cls()
  1379. copy.status = self.status
  1380. copy._headers = dict((k, v[:]) for (k, v) in self._headers.items())
  1381. if self._cookies:
  1382. copy._cookies = SimpleCookie()
  1383. copy._cookies.load(self._cookies.output(header=""))
  1384. return copy
  1385. def __iter__(self):
  1386. return iter(self.body)
  1387. def close(self):
  1388. if hasattr(self.body, "close"):
  1389. self.body.close()
  1390. @property
  1391. def status_line(self):
  1392. """The HTTP status line as a string (e.g. ``404 Not Found``)."""
  1393. return self._status_line
  1394. @property
  1395. def status_code(self):
  1396. """The HTTP status code as an integer (e.g. 404)."""
  1397. return self._status_code
  1398. def _set_status(self, status):
  1399. if isinstance(status, int):
  1400. code, status = status, _HTTP_STATUS_LINES.get(status)
  1401. elif " " in status:
  1402. status = status.strip()
  1403. code = int(status.split()[0])
  1404. else:
  1405. raise ValueError("String status line without a reason phrase.")
  1406. if not 100 <= code <= 999:
  1407. raise ValueError("Status code out of range.")
  1408. self._status_code = code
  1409. self._status_line = str(status or ("%d Unknown" % code))
  1410. def _get_status(self):
  1411. return self._status_line
  1412. status = property(
  1413. _get_status,
  1414. _set_status,
  1415. None,
  1416. """ A writeable property to change the HTTP response status. It accepts
  1417. either a numeric code (100-999) or a string with a custom reason
  1418. phrase (e.g. "404 Brain not found"). Both :data:`status_line` and
  1419. :data:`status_code` are updated accordingly. The return value is
  1420. always a status string. """,
  1421. )
  1422. del _get_status, _set_status
  1423. @property
  1424. def headers(self):
  1425. """An instance of :class:`HeaderDict`, a case-insensitive dict-like
  1426. view on the response headers."""
  1427. hdict = HeaderDict()
  1428. hdict.dict = self._headers
  1429. return hdict
  1430. def __contains__(self, name):
  1431. return _hkey(name) in self._headers
  1432. def __delitem__(self, name):
  1433. del self._headers[_hkey(name)]
  1434. def __getitem__(self, name):
  1435. return self._headers[_hkey(name)][-1]
  1436. def __setitem__(self, name, value):
  1437. self._headers[_hkey(name)] = [_hval(value)]
  1438. def get_header(self, name, default=None):
  1439. """Return the value of a previously defined header. If there is no
  1440. header with that name, return a default value."""
  1441. return self._headers.get(_hkey(name), [default])[-1]
  1442. def set_header(self, name, value):
  1443. """Create a new response header, replacing any previously defined
  1444. headers with the same name."""
  1445. self._headers[_hkey(name)] = [_hval(value)]
  1446. def add_header(self, name, value):
  1447. """Add an additional response header, not removing duplicates."""
  1448. self._headers.setdefault(_hkey(name), []).append(_hval(value))
  1449. def iter_headers(self):
  1450. """Yield (header, value) tuples, skipping headers that are not
  1451. allowed with the current response status code."""
  1452. return self.headerlist
  1453. @property
  1454. def headerlist(self):
  1455. """WSGI conform list of (header, value) tuples."""
  1456. out = []
  1457. headers = list(self._headers.items())
  1458. if "Content-Type" not in self._headers:
  1459. headers.append(("Content-Type", [self.default_content_type]))
  1460. if self._status_code in self.bad_headers:
  1461. bad_headers = self.bad_headers[self._status_code]
  1462. headers = [h for h in headers if h[0] not in bad_headers]
  1463. out += [(name, val) for (name, vals) in headers for val in vals]
  1464. if self._cookies:
  1465. for c in self._cookies.values():
  1466. out.append(("Set-Cookie", _hval(c.OutputString())))
  1467. if py3k:
  1468. out = [(k, v.encode("utf8").decode("latin1")) for (k, v) in out]
  1469. return out
  1470. content_type = HeaderProperty("Content-Type")
  1471. content_length = HeaderProperty("Content-Length", reader=int)
  1472. expires = HeaderProperty(
  1473. "Expires",
  1474. reader=lambda x: datetime.utcfromtimestamp(parse_date(x)),
  1475. writer=lambda x: http_date(x),
  1476. )
  1477. @property
  1478. def charset(self, default="UTF-8"):
  1479. """Return the charset specified in the content-type header (default: utf8)."""
  1480. if "charset=" in self.content_type:
  1481. return self.content_type.split("charset=")[-1].split(";")[0].strip()
  1482. return default
  1483. def set_cookie(self, name, value, secret=None, **options):
  1484. """Create a new cookie or replace an old one. If the `secret` parameter is
  1485. set, create a `Signed Cookie` (described below).
  1486. :param name: the name of the cookie.
  1487. :param value: the value of the cookie.
  1488. :param secret: a signature key required for signed cookies.
  1489. Additionally, this method accepts all RFC 2109 attributes that are
  1490. supported by :class:`cookie.Morsel`, including:
  1491. :param max_age: maximum age in seconds. (default: None)
  1492. :param expires: a datetime object or UNIX timestamp. (default: None)
  1493. :param domain: the domain that is allowed to read the cookie.
  1494. (default: current domain)
  1495. :param path: limits the cookie to a given path (default: current path)
  1496. :param secure: limit the cookie to HTTPS connections (default: off).
  1497. :param httponly: prevents client-side javascript to read this cookie
  1498. (default: off, requires Python 2.6 or newer).
  1499. If neither `expires` nor `max_age` is set (default), the cookie will
  1500. expire at the end of the browser session (as soon as the browser
  1501. window is closed).
  1502. Signed cookies may store any pickle-able object and are
  1503. cryptographically signed to prevent manipulation. Keep in mind that
  1504. cookies are limited to 4kb in most browsers.
  1505. Warning: Signed cookies are not encrypted (the client can still see
  1506. the content) and not copy-protected (the client can restore an old
  1507. cookie). The main intention is to make pickling and unpickling
  1508. save, not to store secret information at client side.
  1509. """
  1510. if not self._cookies:
  1511. self._cookies = SimpleCookie()
  1512. if secret:
  1513. value = touni(cookie_encode((name, value), secret))
  1514. elif not isinstance(value, basestring):
  1515. raise TypeError("Secret key missing for non-string Cookie.")
  1516. if len(value) > 4096:
  1517. raise ValueError("Cookie value to long.")
  1518. self._cookies[name] = value
  1519. for key, value in options.items():
  1520. if key == "max_age":
  1521. if isinstance(value, timedelta):
  1522. value = value.seconds + value.days * 24 * 3600
  1523. if key == "expires":
  1524. if isinstance(value, (datedate, datetime)):
  1525. value = value.timetuple()
  1526. elif isinstance(value, (int, float)):
  1527. value = time.gmtime(value)
  1528. value = time.strftime("%a, %d %b %Y %H:%M:%S GMT", value)
  1529. self._cookies[name][key.replace("_", "-")] = value
  1530. def delete_cookie(self, key, **kwargs):
  1531. """Delete a cookie. Be sure to use the same `domain` and `path`
  1532. settings as used to create the cookie."""
  1533. kwargs["max_age"] = -1
  1534. kwargs["expires"] = 0
  1535. self.set_cookie(key, "", **kwargs)
  1536. def __repr__(self):
  1537. out = ""
  1538. for name, value in self.headerlist:
  1539. out += "%s: %s\n" % (name.title(), value.strip())
  1540. return out
  1541. def local_property(name=None):
  1542. if name:
  1543. depr("local_property() is deprecated and will be removed.") # 0.12
  1544. ls = threading.local()
  1545. def fget(self):
  1546. try:
  1547. return ls.var
  1548. except AttributeError:
  1549. raise RuntimeError("Request context not initialized.")
  1550. def fset(self, value):
  1551. ls.var = value
  1552. def fdel(self):
  1553. del ls.var
  1554. return property(fget, fset, fdel, "Thread-local property")
  1555. class LocalRequest(BaseRequest):
  1556. """A thread-local subclass of :class:`BaseRequest` with a different
  1557. set of attributes for each thread. There is usually only one global
  1558. instance of this class (:data:`request`). If accessed during a
  1559. request/response cycle, this instance always refers to the *current*
  1560. request (even on a multithreaded server)."""
  1561. bind = BaseRequest.__init__
  1562. environ = local_property()
  1563. class LocalResponse(BaseResponse):
  1564. """A thread-local subclass of :class:`BaseResponse` with a different
  1565. set of attributes for each thread. There is usually only one global
  1566. instance of this class (:data:`response`). Its attributes are used
  1567. to build the HTTP response at the end of the request/response cycle.
  1568. """
  1569. bind = BaseResponse.__init__
  1570. _status_line = local_property()
  1571. _status_code = local_property()
  1572. _cookies = local_property()
  1573. _headers = local_property()
  1574. body = local_property()
  1575. Request = BaseRequest
  1576. Response = BaseResponse
  1577. class HTTPResponse(Response, BottleException):
  1578. def __init__(self, body="", status=None, headers=None, **more_headers):
  1579. super(HTTPResponse, self).__init__(body, status, headers, **more_headers)
  1580. def apply(self, response):
  1581. response._status_code = self._status_code
  1582. response._status_line = self._status_line
  1583. response._headers = self._headers
  1584. response._cookies = self._cookies
  1585. response.body = self.body
  1586. class HTTPError(HTTPResponse):
  1587. default_status = 500
  1588. def __init__(
  1589. self, status=None, body=None, exception=None, traceback=None, **options
  1590. ):
  1591. self.exception = exception
  1592. self.traceback = traceback
  1593. super(HTTPError, self).__init__(body, status, **options)
  1594. ###############################################################################
  1595. # Plugins ######################################################################
  1596. ###############################################################################
  1597. class PluginError(BottleException):
  1598. pass
  1599. class JSONPlugin(object):
  1600. name = "json"
  1601. api = 2
  1602. def __init__(self, json_dumps=json_dumps):
  1603. self.json_dumps = json_dumps
  1604. def apply(self, callback, route):
  1605. dumps = self.json_dumps
  1606. if not dumps:
  1607. return callback
  1608. def wrapper(*a, **ka):
  1609. try:
  1610. rv = callback(*a, **ka)
  1611. except HTTPResponse:
  1612. rv = _e()
  1613. if isinstance(rv, dict):
  1614. # Attempt to serialize, raises exception on failure
  1615. json_response = dumps(rv)
  1616. # Set content type only if serialization successful
  1617. response.content_type = "application/json"
  1618. return json_response
  1619. elif isinstance(rv, HTTPResponse) and isinstance(rv.body, dict):
  1620. rv.body = dumps(rv.body)
  1621. rv.content_type = "application/json"
  1622. return rv
  1623. return wrapper
  1624. class TemplatePlugin(object):
  1625. """This plugin applies the :func:`view` decorator to all routes with a
  1626. `template` config parameter. If the parameter is a tuple, the second
  1627. element must be a dict with additional options (e.g. `template_engine`)
  1628. or default variables for the template."""
  1629. name = "template"
  1630. api = 2
  1631. def apply(self, callback, route):
  1632. conf = route.config.get("template")
  1633. if isinstance(conf, (tuple, list)) and len(conf) == 2:
  1634. return view(conf[0], **conf[1])(callback)
  1635. elif isinstance(conf, str):
  1636. return view(conf)(callback)
  1637. else:
  1638. return callback
  1639. #: Not a plugin, but part of the plugin API. TODO: Find a better place.
  1640. class _ImportRedirect(object):
  1641. def __init__(self, name, impmask):
  1642. """Create a virtual package that redirects imports (see PEP 302)."""
  1643. self.name = name
  1644. self.impmask = impmask
  1645. self.module = sys.modules.setdefault(name, new_module(name))
  1646. self.module.__dict__.update(
  1647. {"__file__": __file__, "__path__": [], "__all__": [], "__loader__": self}
  1648. )
  1649. sys.meta_path.append(self)
  1650. def find_module(self, fullname, path=None):
  1651. if "." not in fullname:
  1652. return
  1653. packname = fullname.rsplit(".", 1)[0]
  1654. if packname != self.name:
  1655. return
  1656. return self
  1657. def load_module(self, fullname):
  1658. if fullname in sys.modules:
  1659. return sys.modules[fullname]
  1660. modname = fullname.rsplit(".", 1)[1]
  1661. realname = self.impmask % modname
  1662. __import__(realname)
  1663. module = sys.modules[fullname] = sys.modules[realname]
  1664. setattr(self.module, modname, module)
  1665. module.__loader__ = self
  1666. return module
  1667. ###############################################################################
  1668. # Common Utilities #############################################################
  1669. ###############################################################################
  1670. class MultiDict(DictMixin):
  1671. """This dict stores multiple values per key, but behaves exactly like a
  1672. normal dict in that it returns only the newest value for any given key.
  1673. There are special methods available to access the full list of values.
  1674. """
  1675. def __init__(self, *a, **k):
  1676. self.dict = dict((k, [v]) for (k, v) in dict(*a, **k).items())
  1677. def __len__(self):
  1678. return len(self.dict)
  1679. def __iter__(self):
  1680. return iter(self.dict)
  1681. def __contains__(self, key):
  1682. return key in self.dict
  1683. def __delitem__(self, key):
  1684. del self.dict[key]
  1685. def __getitem__(self, key):
  1686. return self.dict[key][-1]
  1687. def __setitem__(self, key, value):
  1688. self.append(key, value)
  1689. def keys(self):
  1690. return self.dict.keys()
  1691. if py3k:
  1692. def values(self):
  1693. return (v[-1] for v in self.dict.values())
  1694. def items(self):
  1695. return ((k, v[-1]) for k, v in self.dict.items())
  1696. def allitems(self):
  1697. return ((k, v) for k, vl in self.dict.items() for v in vl)
  1698. iterkeys = keys
  1699. itervalues = values
  1700. iteritems = items
  1701. iterallitems = allitems
  1702. else:
  1703. def values(self):
  1704. return [v[-1] for v in self.dict.values()]
  1705. def items(self):
  1706. return [(k, v[-1]) for k, v in self.dict.items()]
  1707. def iterkeys(self):
  1708. return self.dict.iterkeys()
  1709. def itervalues(self):
  1710. return (v[-1] for v in self.dict.itervalues())
  1711. def iteritems(self):
  1712. return ((k, v[-1]) for k, v in self.dict.iteritems())
  1713. def iterallitems(self):
  1714. return ((k, v) for k, vl in self.dict.iteritems() for v in vl)
  1715. def allitems(self):
  1716. return [(k, v) for k, vl in self.dict.iteritems() for v in vl]
  1717. def get(self, key, default=None, index=-1, type=None):
  1718. """Return the most recent value for a key.
  1719. :param default: The default value to be returned if the key is not
  1720. present or the type conversion fails.
  1721. :param index: An index for the list of available values.
  1722. :param type: If defined, this callable is used to cast the value
  1723. into a specific type. Exception are suppressed and result in
  1724. the default value to be returned.
  1725. """
  1726. try:
  1727. val = self.dict[key][index]
  1728. return type(val) if type else val
  1729. except Exception:
  1730. pass
  1731. return default
  1732. def append(self, key, value):
  1733. """Add a new value to the list of values for this key."""
  1734. self.dict.setdefault(key, []).append(value)
  1735. def replace(self, key, value):
  1736. """Replace the list of values with a single value."""
  1737. self.dict[key] = [value]
  1738. def getall(self, key):
  1739. """Return a (possibly empty) list of values for a key."""
  1740. return self.dict.get(key) or []
  1741. #: Aliases for WTForms to mimic other multi-dict APIs (Django)
  1742. getone = get
  1743. getlist = getall
  1744. class FormsDict(MultiDict):
  1745. """This :class:`MultiDict` subclass is used to store request form data.
  1746. Additionally to the normal dict-like item access methods (which return
  1747. unmodified data as native strings), this container also supports
  1748. attribute-like access to its values. Attributes are automatically de-
  1749. or recoded to match :attr:`input_encoding` (default: 'utf8'). Missing
  1750. attributes default to an empty string."""
  1751. #: Encoding used for attribute values.
  1752. input_encoding = "utf8"
  1753. #: If true (default), unicode strings are first encoded with `latin1`
  1754. #: and then decoded to match :attr:`input_encoding`.
  1755. recode_unicode = True
  1756. def _fix(self, s, encoding=None):
  1757. if isinstance(s, unicode) and self.recode_unicode: # Python 3 WSGI
  1758. return s.encode("latin1").decode(encoding or self.input_encoding)
  1759. elif isinstance(s, bytes): # Python 2 WSGI
  1760. return s.decode(encoding or self.input_encoding)
  1761. else:
  1762. return s
  1763. def decode(self, encoding=None):
  1764. """Returns a copy with all keys and values de- or recoded to match
  1765. :attr:`input_encoding`. Some libraries (e.g. WTForms) want a
  1766. unicode dictionary."""
  1767. copy = FormsDict()
  1768. enc = copy.input_encoding = encoding or self.input_encoding
  1769. copy.recode_unicode = False
  1770. for key, value in self.allitems():
  1771. copy.append(self._fix(key, enc), self._fix(value, enc))
  1772. return copy
  1773. def getunicode(self, name, default=None, encoding=None):
  1774. """Return the value as a unicode string, or the default."""
  1775. try:
  1776. return self._fix(self[name], encoding)
  1777. except (UnicodeError, KeyError):
  1778. return default
  1779. def __getattr__(self, name, default=unicode()):
  1780. # Without this guard, pickle generates a cryptic TypeError:
  1781. if name.startswith("__") and name.endswith("__"):
  1782. return super(FormsDict, self).__getattr__(name)
  1783. return self.getunicode(name, default=default)
  1784. class HeaderDict(MultiDict):
  1785. """A case-insensitive version of :class:`MultiDict` that defaults to
  1786. replace the old value instead of appending it."""
  1787. def __init__(self, *a, **ka):
  1788. self.dict = {}
  1789. if a or ka:
  1790. self.update(*a, **ka)
  1791. def __contains__(self, key):
  1792. return _hkey(key) in self.dict
  1793. def __delitem__(self, key):
  1794. del self.dict[_hkey(key)]
  1795. def __getitem__(self, key):
  1796. return self.dict[_hkey(key)][-1]
  1797. def __setitem__(self, key, value):
  1798. self.dict[_hkey(key)] = [_hval(value)]
  1799. def append(self, key, value):
  1800. self.dict.setdefault(_hkey(key), []).append(_hval(value))
  1801. def replace(self, key, value):
  1802. self.dict[_hkey(key)] = [_hval(value)]
  1803. def getall(self, key):
  1804. return self.dict.get(_hkey(key)) or []
  1805. def get(self, key, default=None, index=-1):
  1806. return MultiDict.get(self, _hkey(key), default, index)
  1807. def filter(self, names):
  1808. for name in (_hkey(n) for n in names):
  1809. if name in self.dict:
  1810. del self.dict[name]
  1811. class WSGIHeaderDict(DictMixin):
  1812. """This dict-like class wraps a WSGI environ dict and provides convenient
  1813. access to HTTP_* fields. Keys and values are native strings
  1814. (2.x bytes or 3.x unicode) and keys are case-insensitive. If the WSGI
  1815. environment contains non-native string values, these are de- or encoded
  1816. using a lossless 'latin1' character set.
  1817. The API will remain stable even on changes to the relevant PEPs.
  1818. Currently PEP 333, 444 and 3333 are supported. (PEP 444 is the only one
  1819. that uses non-native strings.)
  1820. """
  1821. #: List of keys that do not have a ``HTTP_`` prefix.
  1822. cgikeys = ("CONTENT_TYPE", "CONTENT_LENGTH")
  1823. def __init__(self, environ):
  1824. self.environ = environ
  1825. def _ekey(self, key):
  1826. """Translate header field name to CGI/WSGI environ key."""
  1827. key = key.replace("-", "_").upper()
  1828. if key in self.cgikeys:
  1829. return key
  1830. return "HTTP_" + key
  1831. def raw(self, key, default=None):
  1832. """Return the header value as is (may be bytes or unicode)."""
  1833. return self.environ.get(self._ekey(key), default)
  1834. def __getitem__(self, key):
  1835. return tonat(self.environ[self._ekey(key)], "latin1")
  1836. def __setitem__(self, key, value):
  1837. raise TypeError("%s is read-only." % self.__class__)
  1838. def __delitem__(self, key):
  1839. raise TypeError("%s is read-only." % self.__class__)
  1840. def __iter__(self):
  1841. for key in self.environ:
  1842. if key[:5] == "HTTP_":
  1843. yield key[5:].replace("_", "-").title()
  1844. elif key in self.cgikeys:
  1845. yield key.replace("_", "-").title()
  1846. def keys(self):
  1847. return [x for x in self]
  1848. def __len__(self):
  1849. return len(self.keys())
  1850. def __contains__(self, key):
  1851. return self._ekey(key) in self.environ
  1852. class ConfigDict(dict):
  1853. """A dict-like configuration storage with additional support for
  1854. namespaces, validators, meta-data, on_change listeners and more.
  1855. This storage is optimized for fast read access. Retrieving a key
  1856. or using non-altering dict methods (e.g. `dict.get()`) has no overhead
  1857. compared to a native dict.
  1858. """
  1859. __slots__ = ("_meta", "_on_change")
  1860. class Namespace(DictMixin):
  1861. def __init__(self, config, namespace):
  1862. self._config = config
  1863. self._prefix = namespace
  1864. def __getitem__(self, key):
  1865. depr(
  1866. "Accessing namespaces as dicts is discouraged. "
  1867. "Only use flat item access: "
  1868. 'cfg["names"]["pace"]["key"] -> cfg["name.space.key"]'
  1869. ) # 0.12
  1870. return self._config[self._prefix + "." + key]
  1871. def __setitem__(self, key, value):
  1872. self._config[self._prefix + "." + key] = value
  1873. def __delitem__(self, key):
  1874. del self._config[self._prefix + "." + key]
  1875. def __iter__(self):
  1876. ns_prefix = self._prefix + "."
  1877. for key in self._config:
  1878. ns, dot, name = key.rpartition(".")
  1879. if ns == self._prefix and name:
  1880. yield name
  1881. def keys(self):
  1882. return [x for x in self]
  1883. def __len__(self):
  1884. return len(self.keys())
  1885. def __contains__(self, key):
  1886. return self._prefix + "." + key in self._config
  1887. def __repr__(self):
  1888. return "<Config.Namespace %s.*>" % self._prefix
  1889. def __str__(self):
  1890. return "<Config.Namespace %s.*>" % self._prefix
  1891. # Deprecated ConfigDict features
  1892. def __getattr__(self, key):
  1893. depr("Attribute access is deprecated.") # 0.12
  1894. if key not in self and key[0].isupper():
  1895. self[key] = ConfigDict.Namespace(self._config, self._prefix + "." + key)
  1896. if key not in self and key.startswith("__"):
  1897. raise AttributeError(key)
  1898. return self.get(key)
  1899. def __setattr__(self, key, value):
  1900. if key in ("_config", "_prefix"):
  1901. self.__dict__[key] = value
  1902. return
  1903. depr("Attribute assignment is deprecated.") # 0.12
  1904. if hasattr(DictMixin, key):
  1905. raise AttributeError("Read-only attribute.")
  1906. if key in self and self[key] and isinstance(self[key], self.__class__):
  1907. raise AttributeError("Non-empty namespace attribute.")
  1908. self[key] = value
  1909. def __delattr__(self, key):
  1910. if key in self:
  1911. val = self.pop(key)
  1912. if isinstance(val, self.__class__):
  1913. prefix = key + "."
  1914. for key in self:
  1915. if key.startswith(prefix):
  1916. del self[prefix + key]
  1917. def __call__(self, *a, **ka):
  1918. depr("Calling ConfDict is deprecated. Use the update() method.") # 0.12
  1919. self.update(*a, **ka)
  1920. return self
  1921. def __init__(self, *a, **ka):
  1922. self._meta = {}
  1923. self._on_change = lambda name, value: None
  1924. if a or ka:
  1925. depr("Constructor does no longer accept parameters.") # 0.12
  1926. self.update(*a, **ka)
  1927. def load_config(self, filename):
  1928. """Load values from an *.ini style config file.
  1929. If the config file contains sections, their names are used as
  1930. namespaces for the values within. The two special sections
  1931. ``DEFAULT`` and ``bottle`` refer to the root namespace (no prefix).
  1932. """
  1933. conf = ConfigParser()
  1934. conf.read(filename)
  1935. for section in conf.sections():
  1936. for key, value in conf.items(section):
  1937. if section not in ("DEFAULT", "bottle"):
  1938. key = section + "." + key
  1939. self[key] = value
  1940. return self
  1941. def load_dict(self, source, namespace="", make_namespaces=False):
  1942. """Import values from a dictionary structure. Nesting can be used to
  1943. represent namespaces.
  1944. >>> ConfigDict().load_dict({'name': {'space': {'key': 'value'}}})
  1945. {'name.space.key': 'value'}
  1946. """
  1947. stack = [(namespace, source)]
  1948. while stack:
  1949. prefix, source = stack.pop()
  1950. if not isinstance(source, dict):
  1951. raise TypeError("Source is not a dict (r)" % type(key))
  1952. for key, value in source.items():
  1953. if not isinstance(key, basestring):
  1954. raise TypeError("Key is not a string (%r)" % type(key))
  1955. full_key = prefix + "." + key if prefix else key
  1956. if isinstance(value, dict):
  1957. stack.append((full_key, value))
  1958. if make_namespaces:
  1959. self[full_key] = self.Namespace(self, full_key)
  1960. else:
  1961. self[full_key] = value
  1962. return self
  1963. def update(self, *a, **ka):
  1964. """If the first parameter is a string, all keys are prefixed with this
  1965. namespace. Apart from that it works just as the usual dict.update().
  1966. Example: ``update('some.namespace', key='value')``"""
  1967. prefix = ""
  1968. if a and isinstance(a[0], basestring):
  1969. prefix = a[0].strip(".") + "."
  1970. a = a[1:]
  1971. for key, value in dict(*a, **ka).items():
  1972. self[prefix + key] = value
  1973. def setdefault(self, key, value):
  1974. if key not in self:
  1975. self[key] = value
  1976. return self[key]
  1977. def __setitem__(self, key, value):
  1978. if not isinstance(key, basestring):
  1979. raise TypeError("Key has type %r (not a string)" % type(key))
  1980. value = self.meta_get(key, "filter", lambda x: x)(value)
  1981. if key in self and self[key] is value:
  1982. return
  1983. self._on_change(key, value)
  1984. dict.__setitem__(self, key, value)
  1985. def __delitem__(self, key):
  1986. dict.__delitem__(self, key)
  1987. def clear(self):
  1988. for key in self:
  1989. del self[key]
  1990. def meta_get(self, key, metafield, default=None):
  1991. """Return the value of a meta field for a key."""
  1992. return self._meta.get(key, {}).get(metafield, default)
  1993. def meta_set(self, key, metafield, value):
  1994. """Set the meta field for a key to a new value. This triggers the
  1995. on-change handler for existing keys."""
  1996. self._meta.setdefault(key, {})[metafield] = value
  1997. if key in self:
  1998. self[key] = self[key]
  1999. def meta_list(self, key):
  2000. """Return an iterable of meta field names defined for a key."""
  2001. return self._meta.get(key, {}).keys()
  2002. # Deprecated ConfigDict features
  2003. def __getattr__(self, key):
  2004. depr("Attribute access is deprecated.") # 0.12
  2005. if key not in self and key[0].isupper():
  2006. self[key] = self.Namespace(self, key)
  2007. if key not in self and key.startswith("__"):
  2008. raise AttributeError(key)
  2009. return self.get(key)
  2010. def __setattr__(self, key, value):
  2011. if key in self.__slots__:
  2012. return dict.__setattr__(self, key, value)
  2013. depr("Attribute assignment is deprecated.") # 0.12
  2014. if hasattr(dict, key):
  2015. raise AttributeError("Read-only attribute.")
  2016. if key in self and self[key] and isinstance(self[key], self.Namespace):
  2017. raise AttributeError("Non-empty namespace attribute.")
  2018. self[key] = value
  2019. def __delattr__(self, key):
  2020. if key in self:
  2021. val = self.pop(key)
  2022. if isinstance(val, self.Namespace):
  2023. prefix = key + "."
  2024. for key in self:
  2025. if key.startswith(prefix):
  2026. del self[prefix + key]
  2027. def __call__(self, *a, **ka):
  2028. depr("Calling ConfDict is deprecated. Use the update() method.") # 0.12
  2029. self.update(*a, **ka)
  2030. return self
  2031. class AppStack(list):
  2032. """A stack-like list. Calling it returns the head of the stack."""
  2033. def __call__(self):
  2034. """Return the current default application."""
  2035. return self[-1]
  2036. def push(self, value=None):
  2037. """Add a new :class:`Bottle` instance to the stack"""
  2038. if not isinstance(value, Bottle):
  2039. value = Bottle()
  2040. self.append(value)
  2041. return value
  2042. class WSGIFileWrapper(object):
  2043. def __init__(self, fp, buffer_size=1024 * 64):
  2044. self.fp, self.buffer_size = fp, buffer_size
  2045. for attr in ("fileno", "close", "read", "readlines", "tell", "seek"):
  2046. if hasattr(fp, attr):
  2047. setattr(self, attr, getattr(fp, attr))
  2048. def __iter__(self):
  2049. buff, read = self.buffer_size, self.read
  2050. while True:
  2051. part = read(buff)
  2052. if not part:
  2053. return
  2054. yield part
  2055. class _closeiter(object):
  2056. """This only exists to be able to attach a .close method to iterators that
  2057. do not support attribute assignment (most of itertools)."""
  2058. def __init__(self, iterator, close=None):
  2059. self.iterator = iterator
  2060. self.close_callbacks = makelist(close)
  2061. def __iter__(self):
  2062. return iter(self.iterator)
  2063. def close(self):
  2064. for func in self.close_callbacks:
  2065. func()
  2066. class ResourceManager(object):
  2067. """This class manages a list of search paths and helps to find and open
  2068. application-bound resources (files).
  2069. :param base: default value for :meth:`add_path` calls.
  2070. :param opener: callable used to open resources.
  2071. :param cachemode: controls which lookups are cached. One of 'all',
  2072. 'found' or 'none'.
  2073. """
  2074. def __init__(self, base="./", opener=open, cachemode="all"):
  2075. self.opener = open
  2076. self.base = base
  2077. self.cachemode = cachemode
  2078. #: A list of search paths. See :meth:`add_path` for details.
  2079. self.path = []
  2080. #: A cache for resolved paths. ``res.cache.clear()`` clears the cache.
  2081. self.cache = {}
  2082. def add_path(self, path, base=None, index=None, create=False):
  2083. """Add a new path to the list of search paths. Return False if the
  2084. path does not exist.
  2085. :param path: The new search path. Relative paths are turned into
  2086. an absolute and normalized form. If the path looks like a file
  2087. (not ending in `/`), the filename is stripped off.
  2088. :param base: Path used to absolutize relative search paths.
  2089. Defaults to :attr:`base` which defaults to ``os.getcwd()``.
  2090. :param index: Position within the list of search paths. Defaults
  2091. to last index (appends to the list).
  2092. The `base` parameter makes it easy to reference files installed
  2093. along with a python module or package::
  2094. res.add_path('./resources/', __file__)
  2095. """
  2096. base = os.path.abspath(os.path.dirname(base or self.base))
  2097. path = os.path.abspath(os.path.join(base, os.path.dirname(path)))
  2098. path += os.sep
  2099. if path in self.path:
  2100. self.path.remove(path)
  2101. if create and not os.path.isdir(path):
  2102. os.makedirs(path)
  2103. if index is None:
  2104. self.path.append(path)
  2105. else:
  2106. self.path.insert(index, path)
  2107. self.cache.clear()
  2108. return os.path.exists(path)
  2109. def __iter__(self):
  2110. """Iterate over all existing files in all registered paths."""
  2111. search = self.path[:]
  2112. while search:
  2113. path = search.pop()
  2114. if not os.path.isdir(path):
  2115. continue
  2116. for name in os.listdir(path):
  2117. full = os.path.join(path, name)
  2118. if os.path.isdir(full):
  2119. search.append(full)
  2120. else:
  2121. yield full
  2122. def lookup(self, name):
  2123. """Search for a resource and return an absolute file path, or `None`.
  2124. The :attr:`path` list is searched in order. The first match is
  2125. returend. Symlinks are followed. The result is cached to speed up
  2126. future lookups."""
  2127. if name not in self.cache or DEBUG:
  2128. for path in self.path:
  2129. fpath = os.path.join(path, name)
  2130. if os.path.isfile(fpath):
  2131. if self.cachemode in ("all", "found"):
  2132. self.cache[name] = fpath
  2133. return fpath
  2134. if self.cachemode == "all":
  2135. self.cache[name] = None
  2136. return self.cache[name]
  2137. def open(self, name, mode="r", *args, **kwargs):
  2138. """Find a resource and return a file object, or raise IOError."""
  2139. fname = self.lookup(name)
  2140. if not fname:
  2141. raise IOError("Resource %r not found." % name)
  2142. return self.opener(fname, mode=mode, *args, **kwargs)
  2143. class FileUpload(object):
  2144. def __init__(self, fileobj, name, filename, headers=None):
  2145. """Wrapper for file uploads."""
  2146. #: Open file(-like) object (BytesIO buffer or temporary file)
  2147. self.file = fileobj
  2148. #: Name of the upload form field
  2149. self.name = name
  2150. #: Raw filename as sent by the client (may contain unsafe characters)
  2151. self.raw_filename = filename
  2152. #: A :class:`HeaderDict` with additional headers (e.g. content-type)
  2153. self.headers = HeaderDict(headers) if headers else HeaderDict()
  2154. content_type = HeaderProperty("Content-Type")
  2155. content_length = HeaderProperty("Content-Length", reader=int, default=-1)
  2156. def get_header(self, name, default=None):
  2157. """Return the value of a header within the mulripart part."""
  2158. return self.headers.get(name, default)
  2159. @cached_property
  2160. def filename(self):
  2161. """Name of the file on the client file system, but normalized to ensure
  2162. file system compatibility. An empty filename is returned as 'empty'.
  2163. Only ASCII letters, digits, dashes, underscores and dots are
  2164. allowed in the final filename. Accents are removed, if possible.
  2165. Whitespace is replaced by a single dash. Leading or tailing dots
  2166. or dashes are removed. The filename is limited to 255 characters.
  2167. """
  2168. fname = self.raw_filename
  2169. if not isinstance(fname, unicode):
  2170. fname = fname.decode("utf8", "ignore")
  2171. fname = normalize("NFKD", fname).encode("ASCII", "ignore").decode("ASCII")
  2172. fname = os.path.basename(fname.replace("\\", os.path.sep))
  2173. fname = re.sub(r"[^a-zA-Z0-9-_.\s]", "", fname).strip()
  2174. fname = re.sub(r"[-\s]+", "-", fname).strip(".-")
  2175. return fname[:255] or "empty"
  2176. def _copy_file(self, fp, chunk_size=2**16):
  2177. read, write, offset = self.file.read, fp.write, self.file.tell()
  2178. while 1:
  2179. buf = read(chunk_size)
  2180. if not buf:
  2181. break
  2182. write(buf)
  2183. self.file.seek(offset)
  2184. def save(self, destination, overwrite=False, chunk_size=2**16):
  2185. """Save file to disk or copy its content to an open file(-like) object.
  2186. If *destination* is a directory, :attr:`filename` is added to the
  2187. path. Existing files are not overwritten by default (IOError).
  2188. :param destination: File path, directory or file(-like) object.
  2189. :param overwrite: If True, replace existing files. (default: False)
  2190. :param chunk_size: Bytes to read at a time. (default: 64kb)
  2191. """
  2192. if isinstance(destination, basestring): # Except file-likes here
  2193. if os.path.isdir(destination):
  2194. destination = os.path.join(destination, self.filename)
  2195. if not overwrite and os.path.exists(destination):
  2196. raise IOError("File exists.")
  2197. with open(destination, "wb") as fp:
  2198. self._copy_file(fp, chunk_size)
  2199. else:
  2200. self._copy_file(destination, chunk_size)
  2201. ###############################################################################
  2202. # Application Helper ###########################################################
  2203. ###############################################################################
  2204. def abort(code=500, text="Unknown Error."):
  2205. """Aborts execution and causes a HTTP error."""
  2206. raise HTTPError(code, text)
  2207. def redirect(url, code=None):
  2208. """Aborts execution and causes a 303 or 302 redirect, depending on
  2209. the HTTP protocol version."""
  2210. if not code:
  2211. code = 303 if request.get("SERVER_PROTOCOL") == "HTTP/1.1" else 302
  2212. res = response.copy(cls=HTTPResponse)
  2213. res.status = code
  2214. res.body = ""
  2215. res.set_header("Location", urljoin(request.url, url))
  2216. raise res
  2217. def _file_iter_range(fp, offset, bytes, maxread=1024 * 1024):
  2218. """Yield chunks from a range in a file. No chunk is bigger than maxread."""
  2219. fp.seek(offset)
  2220. while bytes > 0:
  2221. part = fp.read(min(bytes, maxread))
  2222. if not part:
  2223. break
  2224. bytes -= len(part)
  2225. yield part
  2226. def static_file(filename, root, mimetype="auto", download=False, charset="UTF-8"):
  2227. """Open a file in a safe way and return :exc:`HTTPResponse` with status
  2228. code 200, 305, 403 or 404. The ``Content-Type``, ``Content-Encoding``,
  2229. ``Content-Length`` and ``Last-Modified`` headers are set if possible.
  2230. Special support for ``If-Modified-Since``, ``Range`` and ``HEAD``
  2231. requests.
  2232. :param filename: Name or path of the file to send.
  2233. :param root: Root path for file lookups. Should be an absolute directory
  2234. path.
  2235. :param mimetype: Defines the content-type header (default: guess from
  2236. file extension)
  2237. :param download: If True, ask the browser to open a `Save as...` dialog
  2238. instead of opening the file with the associated program. You can
  2239. specify a custom filename as a string. If not specified, the
  2240. original filename is used (default: False).
  2241. :param charset: The charset to use for files with a ``text/*``
  2242. mime-type. (default: UTF-8)
  2243. """
  2244. root = os.path.abspath(root) + os.sep
  2245. filename = os.path.abspath(os.path.join(root, filename.strip("/\\")))
  2246. headers = dict()
  2247. if not filename.startswith(root):
  2248. return HTTPError(403, "Access denied.")
  2249. if not os.path.exists(filename) or not os.path.isfile(filename):
  2250. return HTTPError(404, "File does not exist.")
  2251. if not os.access(filename, os.R_OK):
  2252. return HTTPError(403, "You do not have permission to access this file.")
  2253. if mimetype == "auto":
  2254. mimetype, encoding = mimetypes.guess_type(filename)
  2255. if encoding:
  2256. headers["Content-Encoding"] = encoding
  2257. if mimetype:
  2258. if mimetype[:5] == "text/" and charset and "charset" not in mimetype:
  2259. mimetype += "; charset=%s" % charset
  2260. headers["Content-Type"] = mimetype
  2261. if download:
  2262. download = os.path.basename(filename if download == True else download)
  2263. headers["Content-Disposition"] = 'attachment; filename="%s"' % download
  2264. stats = os.stat(filename)
  2265. headers["Content-Length"] = clen = stats.st_size
  2266. lm = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(stats.st_mtime))
  2267. headers["Last-Modified"] = lm
  2268. ims = request.environ.get("HTTP_IF_MODIFIED_SINCE")
  2269. if ims:
  2270. ims = parse_date(ims.split(";")[0].strip())
  2271. if ims is not None and ims >= int(stats.st_mtime):
  2272. headers["Date"] = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime())
  2273. return HTTPResponse(status=304, **headers)
  2274. body = "" if request.method == "HEAD" else open(filename, "rb")
  2275. headers["Accept-Ranges"] = "bytes"
  2276. ranges = request.environ.get("HTTP_RANGE")
  2277. if "HTTP_RANGE" in request.environ:
  2278. ranges = list(parse_range_header(request.environ["HTTP_RANGE"], clen))
  2279. if not ranges:
  2280. return HTTPError(416, "Requested Range Not Satisfiable")
  2281. offset, end = ranges[0]
  2282. headers["Content-Range"] = "bytes %d-%d/%d" % (offset, end - 1, clen)
  2283. headers["Content-Length"] = str(end - offset)
  2284. if body:
  2285. body = _file_iter_range(body, offset, end - offset)
  2286. return HTTPResponse(body, status=206, **headers)
  2287. return HTTPResponse(body, **headers)
  2288. ###############################################################################
  2289. # HTTP Utilities and MISC (TODO) ###############################################
  2290. ###############################################################################
  2291. def debug(mode=True):
  2292. """Change the debug level.
  2293. There is only one debug level supported at the moment."""
  2294. global DEBUG
  2295. if mode:
  2296. warnings.simplefilter("default")
  2297. DEBUG = bool(mode)
  2298. def http_date(value):
  2299. if isinstance(value, (datedate, datetime)):
  2300. value = value.utctimetuple()
  2301. elif isinstance(value, (int, float)):
  2302. value = time.gmtime(value)
  2303. if not isinstance(value, basestring):
  2304. value = time.strftime("%a, %d %b %Y %H:%M:%S GMT", value)
  2305. return value
  2306. def parse_date(ims):
  2307. """Parse rfc1123, rfc850 and asctime timestamps and return UTC epoch."""
  2308. try:
  2309. ts = email.utils.parsedate_tz(ims)
  2310. return time.mktime(ts[:8] + (0,)) - (ts[9] or 0) - time.timezone
  2311. except (TypeError, ValueError, IndexError, OverflowError):
  2312. return None
  2313. def parse_auth(header):
  2314. """Parse rfc2617 HTTP authentication header string (basic) and return (user,pass) tuple or None"""
  2315. try:
  2316. method, data = header.split(None, 1)
  2317. if method.lower() == "basic":
  2318. user, pwd = touni(base64.b64decode(tob(data))).split(":", 1)
  2319. return user, pwd
  2320. except (KeyError, ValueError):
  2321. return None
  2322. def parse_range_header(header, maxlen=0):
  2323. """Yield (start, end) ranges parsed from a HTTP Range header. Skip
  2324. unsatisfiable ranges. The end index is non-inclusive."""
  2325. if not header or header[:6] != "bytes=":
  2326. return
  2327. ranges = [r.split("-", 1) for r in header[6:].split(",") if "-" in r]
  2328. for start, end in ranges:
  2329. try:
  2330. if not start: # bytes=-100 -> last 100 bytes
  2331. start, end = max(0, maxlen - int(end)), maxlen
  2332. elif not end: # bytes=100- -> all but the first 99 bytes
  2333. start, end = int(start), maxlen
  2334. else: # bytes=100-200 -> bytes 100-200 (inclusive)
  2335. start, end = int(start), min(int(end) + 1, maxlen)
  2336. if 0 <= start < end <= maxlen:
  2337. yield start, end
  2338. except ValueError:
  2339. pass
  2340. def _parse_qsl(qs):
  2341. r = []
  2342. for pair in qs.split("&"):
  2343. if not pair:
  2344. continue
  2345. nv = pair.split("=", 1)
  2346. if len(nv) != 2:
  2347. nv.append("")
  2348. key = urlunquote(nv[0].replace("+", " "))
  2349. value = urlunquote(nv[1].replace("+", " "))
  2350. r.append((key, value))
  2351. return r
  2352. def _lscmp(a, b):
  2353. """Compares two strings in a cryptographically safe way:
  2354. Runtime is not affected by length of common prefix."""
  2355. return not sum(0 if x == y else 1 for x, y in zip(a, b)) and len(a) == len(b)
  2356. def cookie_encode(data, key):
  2357. """Encode and sign a pickle-able object. Return a (byte) string"""
  2358. msg = base64.b64encode(pickle.dumps(data, -1))
  2359. sig = base64.b64encode(hmac.new(tob(key), msg, digestmod=hashlib.md5).digest())
  2360. return tob("!") + sig + tob("?") + msg
  2361. def cookie_decode(data, key):
  2362. """Verify and decode an encoded string. Return an object or None."""
  2363. data = tob(data)
  2364. if cookie_is_encoded(data):
  2365. sig, msg = data.split(tob("?"), 1)
  2366. if _lscmp(
  2367. sig[1:],
  2368. base64.b64encode(hmac.new(tob(key), msg, digestmod=hashlib.md5).digest()),
  2369. ):
  2370. return pickle.loads(base64.b64decode(msg))
  2371. return None
  2372. def cookie_is_encoded(data):
  2373. """Return True if the argument looks like a encoded cookie."""
  2374. return bool(data.startswith(tob("!")) and tob("?") in data)
  2375. def html_escape(string):
  2376. """Escape HTML special characters ``&<>`` and quotes ``'"``."""
  2377. return (
  2378. string.replace("&", "&amp;")
  2379. .replace("<", "&lt;")
  2380. .replace(">", "&gt;")
  2381. .replace('"', "&quot;")
  2382. .replace("'", "&#039;")
  2383. )
  2384. def html_quote(string):
  2385. """Escape and quote a string to be used as an HTTP attribute."""
  2386. return '"%s"' % html_escape(string).replace("\n", "&#10;").replace(
  2387. "\r", "&#13;"
  2388. ).replace("\t", "&#9;")
  2389. def yieldroutes(func):
  2390. """Return a generator for routes that match the signature (name, args)
  2391. of the func parameter. This may yield more than one route if the function
  2392. takes optional keyword arguments. The output is best described by example::
  2393. a() -> '/a'
  2394. b(x, y) -> '/b/<x>/<y>'
  2395. c(x, y=5) -> '/c/<x>' and '/c/<x>/<y>'
  2396. d(x=5, y=6) -> '/d' and '/d/<x>' and '/d/<x>/<y>'
  2397. """
  2398. path = "/" + func.__name__.replace("__", "/").lstrip("/")
  2399. spec = getargspec(func)
  2400. argc = len(spec[0]) - len(spec[3] or [])
  2401. path += ("/<%s>" * argc) % tuple(spec[0][:argc])
  2402. yield path
  2403. for arg in spec[0][argc:]:
  2404. path += "/<%s>" % arg
  2405. yield path
  2406. def path_shift(script_name, path_info, shift=1):
  2407. """Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa.
  2408. :return: The modified paths.
  2409. :param script_name: The SCRIPT_NAME path.
  2410. :param script_name: The PATH_INFO path.
  2411. :param shift: The number of path fragments to shift. May be negative to
  2412. change the shift direction. (default: 1)
  2413. """
  2414. if shift == 0:
  2415. return script_name, path_info
  2416. pathlist = path_info.strip("/").split("/")
  2417. scriptlist = script_name.strip("/").split("/")
  2418. if pathlist and pathlist[0] == "":
  2419. pathlist = []
  2420. if scriptlist and scriptlist[0] == "":
  2421. scriptlist = []
  2422. if shift > 0 and shift <= len(pathlist):
  2423. moved = pathlist[:shift]
  2424. scriptlist = scriptlist + moved
  2425. pathlist = pathlist[shift:]
  2426. elif shift < 0 and shift >= -len(scriptlist):
  2427. moved = scriptlist[shift:]
  2428. pathlist = moved + pathlist
  2429. scriptlist = scriptlist[:shift]
  2430. else:
  2431. empty = "SCRIPT_NAME" if shift < 0 else "PATH_INFO"
  2432. raise AssertionError("Cannot shift. Nothing left from %s" % empty)
  2433. new_script_name = "/" + "/".join(scriptlist)
  2434. new_path_info = "/" + "/".join(pathlist)
  2435. if path_info.endswith("/") and pathlist:
  2436. new_path_info += "/"
  2437. return new_script_name, new_path_info
  2438. def auth_basic(check, realm="private", text="Access denied"):
  2439. """Callback decorator to require HTTP auth (basic).
  2440. TODO: Add route(check_auth=...) parameter."""
  2441. def decorator(func):
  2442. @functools.wraps(func)
  2443. def wrapper(*a, **ka):
  2444. user, password = request.auth or (None, None)
  2445. if user is None or not check(user, password):
  2446. err = HTTPError(401, text)
  2447. err.add_header("WWW-Authenticate", 'Basic realm="%s"' % realm)
  2448. return err
  2449. return func(*a, **ka)
  2450. return wrapper
  2451. return decorator
  2452. # Shortcuts for common Bottle methods.
  2453. # They all refer to the current default application.
  2454. def make_default_app_wrapper(name):
  2455. """Return a callable that relays calls to the current default app."""
  2456. @functools.wraps(getattr(Bottle, name))
  2457. def wrapper(*a, **ka):
  2458. return getattr(app(), name)(*a, **ka)
  2459. return wrapper
  2460. route = make_default_app_wrapper("route")
  2461. get = make_default_app_wrapper("get")
  2462. post = make_default_app_wrapper("post")
  2463. put = make_default_app_wrapper("put")
  2464. delete = make_default_app_wrapper("delete")
  2465. error = make_default_app_wrapper("error")
  2466. mount = make_default_app_wrapper("mount")
  2467. hook = make_default_app_wrapper("hook")
  2468. install = make_default_app_wrapper("install")
  2469. uninstall = make_default_app_wrapper("uninstall")
  2470. url = make_default_app_wrapper("get_url")
  2471. ###############################################################################
  2472. # Server Adapter ###############################################################
  2473. ###############################################################################
  2474. class ServerAdapter(object):
  2475. quiet = False
  2476. def __init__(self, host="127.0.0.1", port=8080, **options):
  2477. self.options = options
  2478. self.host = host
  2479. self.port = int(port)
  2480. def run(self, handler): # pragma: no cover
  2481. pass
  2482. def __repr__(self):
  2483. args = ", ".join(["%s=%s" % (k, repr(v)) for k, v in self.options.items()])
  2484. return "%s(%s)" % (self.__class__.__name__, args)
  2485. class CGIServer(ServerAdapter):
  2486. quiet = True
  2487. def run(self, handler): # pragma: no cover
  2488. from wsgiref.handlers import CGIHandler
  2489. def fixed_environ(environ, start_response):
  2490. environ.setdefault("PATH_INFO", "")
  2491. return handler(environ, start_response)
  2492. CGIHandler().run(fixed_environ)
  2493. class FlupFCGIServer(ServerAdapter):
  2494. def run(self, handler): # pragma: no cover
  2495. import flup.server.fcgi
  2496. self.options.setdefault("bindAddress", (self.host, self.port))
  2497. flup.server.fcgi.WSGIServer(handler, **self.options).run()
  2498. class WSGIRefServer(ServerAdapter):
  2499. def run(self, app): # pragma: no cover
  2500. from wsgiref.simple_server import WSGIRequestHandler, WSGIServer
  2501. from wsgiref.simple_server import make_server
  2502. import socket
  2503. class FixedHandler(WSGIRequestHandler):
  2504. def address_string(self): # Prevent reverse DNS lookups please.
  2505. return self.client_address[0]
  2506. def log_request(*args, **kw):
  2507. if not self.quiet:
  2508. return WSGIRequestHandler.log_request(*args, **kw)
  2509. handler_cls = self.options.get("handler_class", FixedHandler)
  2510. server_cls = self.options.get("server_class", WSGIServer)
  2511. if ":" in self.host: # Fix wsgiref for IPv6 addresses.
  2512. if getattr(server_cls, "address_family") == socket.AF_INET:
  2513. class server_cls(server_cls):
  2514. address_family = socket.AF_INET6
  2515. srv = make_server(self.host, self.port, app, server_cls, handler_cls)
  2516. srv.serve_forever()
  2517. class CherryPyServer(ServerAdapter):
  2518. def run(self, handler): # pragma: no cover
  2519. depr(
  2520. "The wsgi server part of cherrypy was split into a new "
  2521. "project called 'cheroot'. Use the 'cheroot' server "
  2522. "adapter instead of cherrypy."
  2523. )
  2524. from cherrypy import wsgiserver # This will fail for CherryPy >= 9
  2525. self.options["bind_addr"] = (self.host, self.port)
  2526. self.options["wsgi_app"] = handler
  2527. certfile = self.options.get("certfile")
  2528. if certfile:
  2529. del self.options["certfile"]
  2530. keyfile = self.options.get("keyfile")
  2531. if keyfile:
  2532. del self.options["keyfile"]
  2533. server = wsgiserver.CherryPyWSGIServer(**self.options)
  2534. if certfile:
  2535. server.ssl_certificate = certfile
  2536. if keyfile:
  2537. server.ssl_private_key = keyfile
  2538. try:
  2539. server.start()
  2540. finally:
  2541. server.stop()
  2542. class CherootServer(ServerAdapter):
  2543. def run(self, handler): # pragma: no cover
  2544. from cheroot import wsgi
  2545. from cheroot.ssl import builtin
  2546. self.options["bind_addr"] = (self.host, self.port)
  2547. self.options["wsgi_app"] = handler
  2548. certfile = self.options.pop("certfile", None)
  2549. keyfile = self.options.pop("keyfile", None)
  2550. chainfile = self.options.pop("chainfile", None)
  2551. server = wsgi.Server(**self.options)
  2552. if certfile and keyfile:
  2553. server.ssl_adapter = builtin.BuiltinSSLAdapter(certfile, keyfile, chainfile)
  2554. try:
  2555. server.start()
  2556. finally:
  2557. server.stop()
  2558. class WaitressServer(ServerAdapter):
  2559. def run(self, handler):
  2560. from waitress import serve
  2561. serve(handler, host=self.host, port=self.port)
  2562. class PasteServer(ServerAdapter):
  2563. def run(self, handler): # pragma: no cover
  2564. from paste import httpserver
  2565. from paste.translogger import TransLogger
  2566. handler = TransLogger(handler, setup_console_handler=(not self.quiet))
  2567. httpserver.serve(handler, host=self.host, port=str(self.port), **self.options)
  2568. class MeinheldServer(ServerAdapter):
  2569. def run(self, handler):
  2570. from meinheld import server
  2571. server.listen((self.host, self.port))
  2572. server.run(handler)
  2573. class FapwsServer(ServerAdapter):
  2574. """Extremely fast webserver using libev. See https://github.com/william-os4y/fapws3"""
  2575. def run(self, handler): # pragma: no cover
  2576. import fapws._evwsgi as evwsgi
  2577. from fapws import base, config
  2578. port = self.port
  2579. if float(config.SERVER_IDENT[-2:]) > 0.4:
  2580. # fapws3 silently changed its API in 0.5
  2581. port = str(port)
  2582. evwsgi.start(self.host, port)
  2583. # fapws3 never releases the GIL. Complain upstream. I tried. No luck.
  2584. if "BOTTLE_CHILD" in os.environ and not self.quiet:
  2585. _stderr("WARNING: Auto-reloading does not work with Fapws3.\n")
  2586. _stderr(" (Fapws3 breaks python thread support)\n")
  2587. evwsgi.set_base_module(base)
  2588. def app(environ, start_response):
  2589. environ["wsgi.multiprocess"] = False
  2590. return handler(environ, start_response)
  2591. evwsgi.wsgi_cb(("", app))
  2592. evwsgi.run()
  2593. class TornadoServer(ServerAdapter):
  2594. """The super hyped asynchronous server by facebook. Untested."""
  2595. def run(self, handler): # pragma: no cover
  2596. import tornado.wsgi, tornado.httpserver, tornado.ioloop
  2597. container = tornado.wsgi.WSGIContainer(handler)
  2598. server = tornado.httpserver.HTTPServer(container)
  2599. server.listen(port=self.port, address=self.host)
  2600. tornado.ioloop.IOLoop.instance().start()
  2601. class AppEngineServer(ServerAdapter):
  2602. """Adapter for Google App Engine."""
  2603. quiet = True
  2604. def run(self, handler):
  2605. from google.appengine.ext.webapp import util
  2606. # A main() function in the handler script enables 'App Caching'.
  2607. # Lets makes sure it is there. This _really_ improves performance.
  2608. module = sys.modules.get("__main__")
  2609. if module and not hasattr(module, "main"):
  2610. module.main = lambda: util.run_wsgi_app(handler)
  2611. util.run_wsgi_app(handler)
  2612. class TwistedServer(ServerAdapter):
  2613. """Untested."""
  2614. def run(self, handler):
  2615. from twisted.web import server, wsgi
  2616. from twisted.python.threadpool import ThreadPool
  2617. from twisted.internet import reactor
  2618. thread_pool = ThreadPool()
  2619. thread_pool.start()
  2620. reactor.addSystemEventTrigger("after", "shutdown", thread_pool.stop)
  2621. factory = server.Site(wsgi.WSGIResource(reactor, thread_pool, handler))
  2622. reactor.listenTCP(self.port, factory, interface=self.host)
  2623. reactor.run()
  2624. class DieselServer(ServerAdapter):
  2625. """Untested."""
  2626. def run(self, handler):
  2627. from diesel.protocols.wsgi import WSGIApplication
  2628. app = WSGIApplication(handler, port=self.port)
  2629. app.run()
  2630. class GeventServer(ServerAdapter):
  2631. """Untested. Options:
  2632. * `fast` (default: False) uses libevent's http server, but has some
  2633. issues: No streaming, no pipelining, no SSL.
  2634. * See gevent.wsgi.WSGIServer() documentation for more options.
  2635. """
  2636. def run(self, handler):
  2637. from gevent import pywsgi, local
  2638. if not isinstance(threading.local(), local.local):
  2639. msg = "Bottle requires gevent.monkey.patch_all() (before import)"
  2640. raise RuntimeError(msg)
  2641. if self.options.pop("fast", None):
  2642. depr('The "fast" option has been deprecated and removed by Gevent.')
  2643. if self.quiet:
  2644. self.options["log"] = None
  2645. address = (self.host, self.port)
  2646. server = pywsgi.WSGIServer(address, handler, **self.options)
  2647. if "BOTTLE_CHILD" in os.environ:
  2648. import signal
  2649. signal.signal(signal.SIGINT, lambda s, f: server.stop())
  2650. server.serve_forever()
  2651. class GeventSocketIOServer(ServerAdapter):
  2652. def run(self, handler):
  2653. from socketio import server
  2654. address = (self.host, self.port)
  2655. server.SocketIOServer(address, handler, **self.options).serve_forever()
  2656. class GunicornServer(ServerAdapter):
  2657. """Untested. See http://gunicorn.org/configure.html for options."""
  2658. def run(self, handler):
  2659. from gunicorn.app.base import Application
  2660. config = {"bind": "%s:%d" % (self.host, int(self.port))}
  2661. config.update(self.options)
  2662. class GunicornApplication(Application):
  2663. def init(self, parser, opts, args):
  2664. return config
  2665. def load(self):
  2666. return handler
  2667. GunicornApplication().run()
  2668. class EventletServer(ServerAdapter):
  2669. """Untested"""
  2670. def run(self, handler):
  2671. from eventlet import wsgi, listen
  2672. try:
  2673. wsgi.server(
  2674. listen((self.host, self.port)), handler, log_output=(not self.quiet)
  2675. )
  2676. except TypeError:
  2677. # Fallback, if we have old version of eventlet
  2678. wsgi.server(listen((self.host, self.port)), handler)
  2679. class RocketServer(ServerAdapter):
  2680. """Untested."""
  2681. def run(self, handler):
  2682. from rocket import Rocket
  2683. server = Rocket((self.host, self.port), "wsgi", {"wsgi_app": handler})
  2684. server.start()
  2685. class BjoernServer(ServerAdapter):
  2686. """Fast server written in C: https://github.com/jonashaag/bjoern"""
  2687. def run(self, handler):
  2688. from bjoern import run
  2689. run(handler, self.host, self.port)
  2690. class AutoServer(ServerAdapter):
  2691. """Untested."""
  2692. adapters = [
  2693. WaitressServer,
  2694. PasteServer,
  2695. TwistedServer,
  2696. CherryPyServer,
  2697. CherootServer,
  2698. WSGIRefServer,
  2699. ]
  2700. def run(self, handler):
  2701. for sa in self.adapters:
  2702. try:
  2703. return sa(self.host, self.port, **self.options).run(handler)
  2704. except ImportError:
  2705. pass
  2706. server_names = {
  2707. "cgi": CGIServer,
  2708. "flup": FlupFCGIServer,
  2709. "wsgiref": WSGIRefServer,
  2710. "waitress": WaitressServer,
  2711. "cherrypy": CherryPyServer,
  2712. "cheroot": CherootServer,
  2713. "paste": PasteServer,
  2714. "fapws3": FapwsServer,
  2715. "tornado": TornadoServer,
  2716. "gae": AppEngineServer,
  2717. "twisted": TwistedServer,
  2718. "diesel": DieselServer,
  2719. "meinheld": MeinheldServer,
  2720. "gunicorn": GunicornServer,
  2721. "eventlet": EventletServer,
  2722. "gevent": GeventServer,
  2723. "geventSocketIO": GeventSocketIOServer,
  2724. "rocket": RocketServer,
  2725. "bjoern": BjoernServer,
  2726. "auto": AutoServer,
  2727. }
  2728. ###############################################################################
  2729. # Application Control ##########################################################
  2730. ###############################################################################
  2731. def load(target, **namespace):
  2732. """Import a module or fetch an object from a module.
  2733. * ``package.module`` returns `module` as a module object.
  2734. * ``pack.mod:name`` returns the module variable `name` from `pack.mod`.
  2735. * ``pack.mod:func()`` calls `pack.mod.func()` and returns the result.
  2736. The last form accepts not only function calls, but any type of
  2737. expression. Keyword arguments passed to this function are available as
  2738. local variables. Example: ``import_string('re:compile(x)', x='[a-z]')``
  2739. """
  2740. module, target = target.split(":", 1) if ":" in target else (target, None)
  2741. if module not in sys.modules:
  2742. __import__(module)
  2743. if not target:
  2744. return sys.modules[module]
  2745. if target.isalnum():
  2746. return getattr(sys.modules[module], target)
  2747. package_name = module.split(".")[0]
  2748. namespace[package_name] = sys.modules[package_name]
  2749. return eval("%s.%s" % (module, target), namespace)
  2750. def load_app(target):
  2751. """Load a bottle application from a module and make sure that the import
  2752. does not affect the current default application, but returns a separate
  2753. application object. See :func:`load` for the target parameter."""
  2754. global NORUN
  2755. NORUN, nr_old = True, NORUN
  2756. try:
  2757. tmp = default_app.push() # Create a new "default application"
  2758. rv = load(target) # Import the target module
  2759. return rv if callable(rv) else tmp
  2760. finally:
  2761. default_app.remove(tmp) # Remove the temporary added default application
  2762. NORUN = nr_old
  2763. _debug = debug
  2764. def run(
  2765. app=None,
  2766. server="wsgiref",
  2767. host="127.0.0.1",
  2768. port=8080,
  2769. interval=1,
  2770. reloader=False,
  2771. quiet=False,
  2772. plugins=None,
  2773. debug=None,
  2774. **kargs
  2775. ):
  2776. """Start a server instance. This method blocks until the server terminates.
  2777. :param app: WSGI application or target string supported by
  2778. :func:`load_app`. (default: :func:`default_app`)
  2779. :param server: Server adapter to use. See :data:`server_names` keys
  2780. for valid names or pass a :class:`ServerAdapter` subclass.
  2781. (default: `wsgiref`)
  2782. :param host: Server address to bind to. Pass ``0.0.0.0`` to listens on
  2783. all interfaces including the external one. (default: 127.0.0.1)
  2784. :param port: Server port to bind to. Values below 1024 require root
  2785. privileges. (default: 8080)
  2786. :param reloader: Start auto-reloading server? (default: False)
  2787. :param interval: Auto-reloader interval in seconds (default: 1)
  2788. :param quiet: Suppress output to stdout and stderr? (default: False)
  2789. :param options: Options passed to the server adapter.
  2790. """
  2791. if NORUN:
  2792. return
  2793. if reloader and not os.environ.get("BOTTLE_CHILD"):
  2794. try:
  2795. lockfile = None
  2796. fd, lockfile = tempfile.mkstemp(prefix="bottle.", suffix=".lock")
  2797. os.close(fd) # We only need this file to exist. We never write to it
  2798. while os.path.exists(lockfile):
  2799. args = [sys.executable] + sys.argv
  2800. environ = os.environ.copy()
  2801. environ["BOTTLE_CHILD"] = "true"
  2802. environ["BOTTLE_LOCKFILE"] = lockfile
  2803. p = subprocess.Popen(args, env=environ)
  2804. while p.poll() is None: # Busy wait...
  2805. os.utime(lockfile, None) # I am alive!
  2806. time.sleep(interval)
  2807. if p.poll() != 3:
  2808. if os.path.exists(lockfile):
  2809. os.unlink(lockfile)
  2810. sys.exit(p.poll())
  2811. except KeyboardInterrupt:
  2812. pass
  2813. finally:
  2814. if os.path.exists(lockfile):
  2815. os.unlink(lockfile)
  2816. return
  2817. try:
  2818. if debug is not None:
  2819. _debug(debug)
  2820. app = app or default_app()
  2821. if isinstance(app, basestring):
  2822. app = load_app(app)
  2823. if not callable(app):
  2824. raise ValueError("Application is not callable: %r" % app)
  2825. for plugin in plugins or []:
  2826. app.install(plugin)
  2827. if server in server_names:
  2828. server = server_names.get(server)
  2829. if isinstance(server, basestring):
  2830. server = load(server)
  2831. if isinstance(server, type):
  2832. server = server(host=host, port=port, **kargs)
  2833. if not isinstance(server, ServerAdapter):
  2834. raise ValueError("Unknown or unsupported server: %r" % server)
  2835. server.quiet = server.quiet or quiet
  2836. if not server.quiet:
  2837. _stderr(
  2838. "Bottle v%s server starting up (using %s)...\n"
  2839. % (__version__, repr(server))
  2840. )
  2841. # _stderr("Listening on http://%s:%d/\n" % (server.host, server.port))
  2842. # _stderr("Hit Ctrl-C to quit.\n\n")
  2843. if reloader:
  2844. lockfile = os.environ.get("BOTTLE_LOCKFILE")
  2845. bgcheck = FileCheckerThread(lockfile, interval)
  2846. with bgcheck:
  2847. server.run(app)
  2848. if bgcheck.status == "reload":
  2849. sys.exit(3)
  2850. else:
  2851. server.run(app)
  2852. except KeyboardInterrupt:
  2853. pass
  2854. except (SystemExit, MemoryError):
  2855. raise
  2856. except:
  2857. if not reloader:
  2858. raise
  2859. if not getattr(server, "quiet", quiet):
  2860. print_exc()
  2861. time.sleep(interval)
  2862. sys.exit(3)
  2863. class FileCheckerThread(threading.Thread):
  2864. """Interrupt main-thread as soon as a changed module file is detected,
  2865. the lockfile gets deleted or gets to old."""
  2866. def __init__(self, lockfile, interval):
  2867. threading.Thread.__init__(self)
  2868. self.lockfile, self.interval = lockfile, interval
  2869. #: Is one of 'reload', 'error' or 'exit'
  2870. self.status = None
  2871. def run(self):
  2872. exists = os.path.exists
  2873. mtime = lambda path: os.stat(path).st_mtime
  2874. files = dict()
  2875. for module in list(sys.modules.values()):
  2876. path = getattr(module, "__file__", "") or ""
  2877. if path[-4:] in (".pyo", ".pyc"):
  2878. path = path[:-1]
  2879. if path and exists(path):
  2880. files[path] = mtime(path)
  2881. while not self.status:
  2882. if (
  2883. not exists(self.lockfile)
  2884. or mtime(self.lockfile) < time.time() - self.interval - 5
  2885. ):
  2886. self.status = "error"
  2887. thread.interrupt_main()
  2888. for path, lmtime in list(files.items()):
  2889. if not exists(path) or mtime(path) > lmtime:
  2890. self.status = "reload"
  2891. thread.interrupt_main()
  2892. break
  2893. time.sleep(self.interval)
  2894. def __enter__(self):
  2895. self.start()
  2896. def __exit__(self, exc_type, exc_val, exc_tb):
  2897. if not self.status:
  2898. self.status = "exit" # silent exit
  2899. self.join()
  2900. return exc_type is not None and issubclass(exc_type, KeyboardInterrupt)
  2901. ###############################################################################
  2902. # Template Adapters ############################################################
  2903. ###############################################################################
  2904. class TemplateError(HTTPError):
  2905. def __init__(self, message):
  2906. HTTPError.__init__(self, 500, message)
  2907. class BaseTemplate(object):
  2908. """Base class and minimal API for template adapters"""
  2909. extensions = ["tpl", "html", "thtml", "stpl"]
  2910. settings = {} # used in prepare()
  2911. defaults = {} # used in render()
  2912. def __init__(self, source=None, name=None, lookup=[], encoding="utf8", **settings):
  2913. """Create a new template.
  2914. If the source parameter (str or buffer) is missing, the name argument
  2915. is used to guess a template filename. Subclasses can assume that
  2916. self.source and/or self.filename are set. Both are strings.
  2917. The lookup, encoding and settings parameters are stored as instance
  2918. variables.
  2919. The lookup parameter stores a list containing directory paths.
  2920. The encoding parameter should be used to decode byte strings or files.
  2921. The settings parameter contains a dict for engine-specific settings.
  2922. """
  2923. self.name = name
  2924. self.source = source.read() if hasattr(source, "read") else source
  2925. self.filename = source.filename if hasattr(source, "filename") else None
  2926. self.lookup = [os.path.abspath(x) for x in lookup]
  2927. self.encoding = encoding
  2928. self.settings = self.settings.copy() # Copy from class variable
  2929. self.settings.update(settings) # Apply
  2930. if not self.source and self.name:
  2931. self.filename = self.search(self.name, self.lookup)
  2932. if not self.filename:
  2933. raise TemplateError("Template %s not found." % repr(name))
  2934. if not self.source and not self.filename:
  2935. raise TemplateError("No template specified.")
  2936. self.prepare(**self.settings)
  2937. @classmethod
  2938. def search(cls, name, lookup=[]):
  2939. """Search name in all directories specified in lookup.
  2940. First without, then with common extensions. Return first hit."""
  2941. if not lookup:
  2942. depr("The template lookup path list should not be empty.") # 0.12
  2943. lookup = ["."]
  2944. if os.path.isabs(name) and os.path.isfile(name):
  2945. depr("Absolute template path names are deprecated.") # 0.12
  2946. return os.path.abspath(name)
  2947. for spath in lookup:
  2948. spath = os.path.abspath(spath) + os.sep
  2949. fname = os.path.abspath(os.path.join(spath, name))
  2950. if not fname.startswith(spath):
  2951. continue
  2952. if os.path.isfile(fname):
  2953. return fname
  2954. for ext in cls.extensions:
  2955. if os.path.isfile("%s.%s" % (fname, ext)):
  2956. return "%s.%s" % (fname, ext)
  2957. @classmethod
  2958. def global_config(cls, key, *args):
  2959. """This reads or sets the global settings stored in class.settings."""
  2960. if args:
  2961. cls.settings = cls.settings.copy() # Make settings local to class
  2962. cls.settings[key] = args[0]
  2963. else:
  2964. return cls.settings[key]
  2965. def prepare(self, **options):
  2966. """Run preparations (parsing, caching, ...).
  2967. It should be possible to call this again to refresh a template or to
  2968. update settings.
  2969. """
  2970. raise NotImplementedError
  2971. def render(self, *args, **kwargs):
  2972. """Render the template with the specified local variables and return
  2973. a single byte or unicode string. If it is a byte string, the encoding
  2974. must match self.encoding. This method must be thread-safe!
  2975. Local variables may be provided in dictionaries (args)
  2976. or directly, as keywords (kwargs).
  2977. """
  2978. raise NotImplementedError
  2979. class MakoTemplate(BaseTemplate):
  2980. def prepare(self, **options):
  2981. from mako.template import Template
  2982. from mako.lookup import TemplateLookup
  2983. options.update({"input_encoding": self.encoding})
  2984. options.setdefault("format_exceptions", bool(DEBUG))
  2985. lookup = TemplateLookup(directories=self.lookup, **options)
  2986. if self.source:
  2987. self.tpl = Template(self.source, lookup=lookup, **options)
  2988. else:
  2989. self.tpl = Template(
  2990. uri=self.name, filename=self.filename, lookup=lookup, **options
  2991. )
  2992. def render(self, *args, **kwargs):
  2993. for dictarg in args:
  2994. kwargs.update(dictarg)
  2995. _defaults = self.defaults.copy()
  2996. _defaults.update(kwargs)
  2997. return self.tpl.render(**_defaults)
  2998. class CheetahTemplate(BaseTemplate):
  2999. def prepare(self, **options):
  3000. from Cheetah.Template import Template
  3001. self.context = threading.local()
  3002. self.context.vars = {}
  3003. options["searchList"] = [self.context.vars]
  3004. if self.source:
  3005. self.tpl = Template(source=self.source, **options)
  3006. else:
  3007. self.tpl = Template(file=self.filename, **options)
  3008. def render(self, *args, **kwargs):
  3009. for dictarg in args:
  3010. kwargs.update(dictarg)
  3011. self.context.vars.update(self.defaults)
  3012. self.context.vars.update(kwargs)
  3013. out = str(self.tpl)
  3014. self.context.vars.clear()
  3015. return out
  3016. class Jinja2Template(BaseTemplate):
  3017. def prepare(self, filters=None, tests=None, globals={}, **kwargs):
  3018. from jinja2 import Environment, FunctionLoader
  3019. if "prefix" in kwargs: # TODO: to be removed after a while
  3020. raise RuntimeError(
  3021. "The keyword argument `prefix` has been removed. "
  3022. "Use the full jinja2 environment name line_statement_prefix instead."
  3023. )
  3024. self.env = Environment(loader=FunctionLoader(self.loader), **kwargs)
  3025. if filters:
  3026. self.env.filters.update(filters)
  3027. if tests:
  3028. self.env.tests.update(tests)
  3029. if globals:
  3030. self.env.globals.update(globals)
  3031. if self.source:
  3032. self.tpl = self.env.from_string(self.source)
  3033. else:
  3034. self.tpl = self.env.get_template(self.filename)
  3035. def render(self, *args, **kwargs):
  3036. for dictarg in args:
  3037. kwargs.update(dictarg)
  3038. _defaults = self.defaults.copy()
  3039. _defaults.update(kwargs)
  3040. return self.tpl.render(**_defaults)
  3041. def loader(self, name):
  3042. fname = self.search(name, self.lookup)
  3043. if not fname:
  3044. return
  3045. with open(fname, "rb") as f:
  3046. return f.read().decode(self.encoding)
  3047. class SimpleTemplate(BaseTemplate):
  3048. def prepare(self, escape_func=html_escape, noescape=False, syntax=None, **ka):
  3049. self.cache = {}
  3050. enc = self.encoding
  3051. self._str = lambda x: touni(x, enc)
  3052. self._escape = lambda x: escape_func(touni(x, enc))
  3053. self.syntax = syntax
  3054. if noescape:
  3055. self._str, self._escape = self._escape, self._str
  3056. @cached_property
  3057. def co(self):
  3058. return compile(self.code, self.filename or "<string>", "exec")
  3059. @cached_property
  3060. def code(self):
  3061. source = self.source
  3062. if not source:
  3063. with open(self.filename, "rb") as f:
  3064. source = f.read()
  3065. try:
  3066. source, encoding = touni(source), "utf8"
  3067. except UnicodeError:
  3068. depr("Template encodings other than utf8 are no longer supported.") # 0.11
  3069. source, encoding = touni(source, "latin1"), "latin1"
  3070. parser = StplParser(source, encoding=encoding, syntax=self.syntax)
  3071. code = parser.translate()
  3072. self.encoding = parser.encoding
  3073. return code
  3074. def _rebase(self, _env, _name=None, **kwargs):
  3075. if _name is None:
  3076. depr(
  3077. "Rebase function called without arguments."
  3078. " You were probably looking for {{base}}?",
  3079. True,
  3080. ) # 0.12
  3081. _env["_rebase"] = (_name, kwargs)
  3082. def _include(self, _env, _name=None, **kwargs):
  3083. if _name is None:
  3084. depr(
  3085. "Rebase function called without arguments."
  3086. " You were probably looking for {{base}}?",
  3087. True,
  3088. ) # 0.12
  3089. env = _env.copy()
  3090. env.update(kwargs)
  3091. if _name not in self.cache:
  3092. self.cache[_name] = self.__class__(name=_name, lookup=self.lookup)
  3093. return self.cache[_name].execute(env["_stdout"], env)
  3094. def execute(self, _stdout, kwargs):
  3095. env = self.defaults.copy()
  3096. env.update(kwargs)
  3097. env.update(
  3098. {
  3099. "_stdout": _stdout,
  3100. "_printlist": _stdout.extend,
  3101. "include": functools.partial(self._include, env),
  3102. "rebase": functools.partial(self._rebase, env),
  3103. "_rebase": None,
  3104. "_str": self._str,
  3105. "_escape": self._escape,
  3106. "get": env.get,
  3107. "setdefault": env.setdefault,
  3108. "defined": env.__contains__,
  3109. }
  3110. )
  3111. eval(self.co, env)
  3112. if env.get("_rebase"):
  3113. subtpl, rargs = env.pop("_rebase")
  3114. rargs["base"] = "".join(_stdout) # copy stdout
  3115. del _stdout[:] # clear stdout
  3116. return self._include(env, subtpl, **rargs)
  3117. return env
  3118. def render(self, *args, **kwargs):
  3119. """Render the template using keyword arguments as local variables."""
  3120. env = {}
  3121. stdout = []
  3122. for dictarg in args:
  3123. env.update(dictarg)
  3124. env.update(kwargs)
  3125. self.execute(stdout, env)
  3126. return "".join(stdout)
  3127. class StplSyntaxError(TemplateError):
  3128. pass
  3129. class StplParser(object):
  3130. """Parser for stpl templates."""
  3131. _re_cache = {} #: Cache for compiled re patterns
  3132. # This huge pile of voodoo magic splits python code into 8 different tokens.
  3133. # 1: All kinds of python strings (trust me, it works)
  3134. _re_tok = (
  3135. "([urbURB]?(?:''(?!')|\"\"(?!\")|'{6}|\"{6}"
  3136. "|'(?:[^\\\\']|\\\\.)+?'|\"(?:[^\\\\\"]|\\\\.)+?\""
  3137. "|'{3}(?:[^\\\\]|\\\\.|\\n)+?'{3}"
  3138. '|"{3}(?:[^\\\\]|\\\\.|\\n)+?"{3}))'
  3139. )
  3140. _re_inl = _re_tok.replace("|\\n", "") # We re-use this string pattern later
  3141. # 2: Comments (until end of line, but not the newline itself)
  3142. _re_tok += "|(#.*)"
  3143. # 3,4: Open and close grouping tokens
  3144. _re_tok += "|([\\[\\{\\(])"
  3145. _re_tok += "|([\\]\\}\\)])"
  3146. # 5,6: Keywords that start or continue a python block (only start of line)
  3147. _re_tok += (
  3148. "|^([ \\t]*(?:if|for|while|with|try|def|class)\\b)"
  3149. "|^([ \\t]*(?:elif|else|except|finally)\\b)"
  3150. )
  3151. # 7: Our special 'end' keyword (but only if it stands alone)
  3152. _re_tok += "|((?:^|;)[ \\t]*end[ \\t]*(?=(?:%(block_close)s[ \\t]*)?\\r?$|;|#))"
  3153. # 8: A customizable end-of-code-block template token (only end of line)
  3154. _re_tok += "|(%(block_close)s[ \\t]*(?=\\r?$))"
  3155. # 9: And finally, a single newline. The 10th token is 'everything else'
  3156. _re_tok += "|(\\r?\\n)"
  3157. # Match the start tokens of code areas in a template
  3158. _re_split = "(?m)^[ \t]*(\\\\?)((%(line_start)s)|(%(block_start)s))(%%?)"
  3159. # Match inline statements (may contain python strings)
  3160. _re_inl = "(?m)%%(inline_start)s((?:%s|[^'\"\n])*?)%%(inline_end)s" % _re_inl
  3161. _re_tok = "(?m)" + _re_tok
  3162. default_syntax = "<% %> % {{ }}"
  3163. def __init__(self, source, syntax=None, encoding="utf8"):
  3164. self.source, self.encoding = touni(source, encoding), encoding
  3165. self.set_syntax(syntax or self.default_syntax)
  3166. self.code_buffer, self.text_buffer = [], []
  3167. self.lineno, self.offset = 1, 0
  3168. self.indent, self.indent_mod = 0, 0
  3169. self.paren_depth = 0
  3170. def get_syntax(self):
  3171. """Tokens as a space separated string (default: <% %> % {{ }})"""
  3172. return self._syntax
  3173. def set_syntax(self, syntax):
  3174. self._syntax = syntax
  3175. self._tokens = syntax.split()
  3176. if not syntax in self._re_cache:
  3177. names = "block_start block_close line_start inline_start inline_end"
  3178. etokens = map(re.escape, self._tokens)
  3179. pattern_vars = dict(zip(names.split(), etokens))
  3180. patterns = (self._re_split, self._re_tok, self._re_inl)
  3181. patterns = [re.compile(p % pattern_vars) for p in patterns]
  3182. self._re_cache[syntax] = patterns
  3183. self.re_split, self.re_tok, self.re_inl = self._re_cache[syntax]
  3184. syntax = property(get_syntax, set_syntax)
  3185. def translate(self):
  3186. if self.offset:
  3187. raise RuntimeError("Parser is a one time instance.")
  3188. while True:
  3189. m = self.re_split.search(self.source[self.offset :])
  3190. if m:
  3191. text = self.source[self.offset : self.offset + m.start()]
  3192. self.text_buffer.append(text)
  3193. self.offset += m.end()
  3194. if m.group(1): # New escape syntax
  3195. line, sep, _ = self.source[self.offset :].partition("\n")
  3196. self.text_buffer.append(m.group(2) + m.group(5) + line + sep)
  3197. self.offset += len(line + sep) + 1
  3198. continue
  3199. elif m.group(5): # Old escape syntax
  3200. depr("Escape code lines with a backslash.") # 0.12
  3201. line, sep, _ = self.source[self.offset :].partition("\n")
  3202. self.text_buffer.append(m.group(2) + line + sep)
  3203. self.offset += len(line + sep) + 1
  3204. continue
  3205. self.flush_text()
  3206. self.read_code(multiline=bool(m.group(4)))
  3207. else:
  3208. break
  3209. self.text_buffer.append(self.source[self.offset :])
  3210. self.flush_text()
  3211. return "".join(self.code_buffer)
  3212. def read_code(self, multiline):
  3213. code_line, comment = "", ""
  3214. while True:
  3215. m = self.re_tok.search(self.source[self.offset :])
  3216. if not m:
  3217. code_line += self.source[self.offset :]
  3218. self.offset = len(self.source)
  3219. self.write_code(code_line.strip(), comment)
  3220. return
  3221. code_line += self.source[self.offset : self.offset + m.start()]
  3222. self.offset += m.end()
  3223. _str, _com, _po, _pc, _blk1, _blk2, _end, _cend, _nl = m.groups()
  3224. if (code_line or self.paren_depth > 0) and (
  3225. _blk1 or _blk2
  3226. ): # a if b else c
  3227. code_line += _blk1 or _blk2
  3228. continue
  3229. if _str: # Python string
  3230. code_line += _str
  3231. elif _com: # Python comment (up to EOL)
  3232. comment = _com
  3233. if multiline and _com.strip().endswith(self._tokens[1]):
  3234. multiline = False # Allow end-of-block in comments
  3235. elif _po: # open parenthesis
  3236. self.paren_depth += 1
  3237. code_line += _po
  3238. elif _pc: # close parenthesis
  3239. if self.paren_depth > 0:
  3240. # we could check for matching parentheses here, but it's
  3241. # easier to leave that to python - just check counts
  3242. self.paren_depth -= 1
  3243. code_line += _pc
  3244. elif _blk1: # Start-block keyword (if/for/while/def/try/...)
  3245. code_line, self.indent_mod = _blk1, -1
  3246. self.indent += 1
  3247. elif _blk2: # Continue-block keyword (else/elif/except/...)
  3248. code_line, self.indent_mod = _blk2, -1
  3249. elif _end: # The non-standard 'end'-keyword (ends a block)
  3250. self.indent -= 1
  3251. elif _cend: # The end-code-block template token (usually '%>')
  3252. if multiline:
  3253. multiline = False
  3254. else:
  3255. code_line += _cend
  3256. else: # \n
  3257. self.write_code(code_line.strip(), comment)
  3258. self.lineno += 1
  3259. code_line, comment, self.indent_mod = "", "", 0
  3260. if not multiline:
  3261. break
  3262. def flush_text(self):
  3263. text = "".join(self.text_buffer)
  3264. del self.text_buffer[:]
  3265. if not text:
  3266. return
  3267. parts, pos, nl = [], 0, "\\\n" + " " * self.indent
  3268. for m in self.re_inl.finditer(text):
  3269. prefix, pos = text[pos : m.start()], m.end()
  3270. if prefix:
  3271. parts.append(nl.join(map(repr, prefix.splitlines(True))))
  3272. if prefix.endswith("\n"):
  3273. parts[-1] += nl
  3274. parts.append(self.process_inline(m.group(1).strip()))
  3275. if pos < len(text):
  3276. prefix = text[pos:]
  3277. lines = prefix.splitlines(True)
  3278. if lines[-1].endswith("\\\\\n"):
  3279. lines[-1] = lines[-1][:-3]
  3280. elif lines[-1].endswith("\\\\\r\n"):
  3281. lines[-1] = lines[-1][:-4]
  3282. parts.append(nl.join(map(repr, lines)))
  3283. code = "_printlist((%s,))" % ", ".join(parts)
  3284. self.lineno += code.count("\n") + 1
  3285. self.write_code(code)
  3286. def process_inline(self, chunk):
  3287. if chunk[0] == "!":
  3288. return "_str(%s)" % chunk[1:]
  3289. return "_escape(%s)" % chunk
  3290. def write_code(self, line, comment=""):
  3291. line, comment = self.fix_backward_compatibility(line, comment)
  3292. code = " " * (self.indent + self.indent_mod)
  3293. code += line.lstrip() + comment + "\n"
  3294. self.code_buffer.append(code)
  3295. def fix_backward_compatibility(self, line, comment):
  3296. parts = line.strip().split(None, 2)
  3297. if parts and parts[0] in ("include", "rebase"):
  3298. depr("The include and rebase keywords are functions now.") # 0.12
  3299. if len(parts) == 1:
  3300. return "_printlist([base])", comment
  3301. elif len(parts) == 2:
  3302. return "_=%s(%r)" % tuple(parts), comment
  3303. else:
  3304. return "_=%s(%r, %s)" % tuple(parts), comment
  3305. if self.lineno <= 2 and not line.strip() and "coding" in comment:
  3306. m = re.match(r"#.*coding[:=]\s*([-\w.]+)", comment)
  3307. if m:
  3308. depr("PEP263 encoding strings in templates are deprecated.") # 0.12
  3309. enc = m.group(1)
  3310. self.source = self.source.encode(self.encoding).decode(enc)
  3311. self.encoding = enc
  3312. return line, comment.replace("coding", "coding*")
  3313. return line, comment
  3314. def template(*args, **kwargs):
  3315. """
  3316. Get a rendered template as a string iterator.
  3317. You can use a name, a filename or a template string as first parameter.
  3318. Template rendering arguments can be passed as dictionaries
  3319. or directly (as keyword arguments).
  3320. """
  3321. tpl = args[0] if args else None
  3322. adapter = kwargs.pop("template_adapter", SimpleTemplate)
  3323. lookup = kwargs.pop("template_lookup", TEMPLATE_PATH)
  3324. tplid = (id(lookup), tpl)
  3325. if tplid not in TEMPLATES or DEBUG:
  3326. settings = kwargs.pop("template_settings", {})
  3327. if isinstance(tpl, adapter):
  3328. TEMPLATES[tplid] = tpl
  3329. if settings:
  3330. TEMPLATES[tplid].prepare(**settings)
  3331. elif "\n" in tpl or "{" in tpl or "%" in tpl or "$" in tpl:
  3332. TEMPLATES[tplid] = adapter(source=tpl, lookup=lookup, **settings)
  3333. else:
  3334. TEMPLATES[tplid] = adapter(name=tpl, lookup=lookup, **settings)
  3335. if not TEMPLATES[tplid]:
  3336. abort(500, "Template (%s) not found" % tpl)
  3337. for dictarg in args[1:]:
  3338. kwargs.update(dictarg)
  3339. return TEMPLATES[tplid].render(kwargs)
  3340. mako_template = functools.partial(template, template_adapter=MakoTemplate)
  3341. cheetah_template = functools.partial(template, template_adapter=CheetahTemplate)
  3342. jinja2_template = functools.partial(template, template_adapter=Jinja2Template)
  3343. def view(tpl_name, **defaults):
  3344. """Decorator: renders a template for a handler.
  3345. The handler can control its behavior like that:
  3346. - return a dict of template vars to fill out the template
  3347. - return something other than a dict and the view decorator will not
  3348. process the template, but return the handler result as is.
  3349. This includes returning a HTTPResponse(dict) to get,
  3350. for instance, JSON with autojson or other castfilters.
  3351. """
  3352. def decorator(func):
  3353. @functools.wraps(func)
  3354. def wrapper(*args, **kwargs):
  3355. result = func(*args, **kwargs)
  3356. if isinstance(result, (dict, DictMixin)):
  3357. tplvars = defaults.copy()
  3358. tplvars.update(result)
  3359. return template(tpl_name, **tplvars)
  3360. elif result is None:
  3361. return template(tpl_name, **defaults)
  3362. return result
  3363. return wrapper
  3364. return decorator
  3365. mako_view = functools.partial(view, template_adapter=MakoTemplate)
  3366. cheetah_view = functools.partial(view, template_adapter=CheetahTemplate)
  3367. jinja2_view = functools.partial(view, template_adapter=Jinja2Template)
  3368. ###############################################################################
  3369. # Constants and Globals ########################################################
  3370. ###############################################################################
  3371. TEMPLATE_PATH = ["./", "./views/"]
  3372. TEMPLATES = {}
  3373. DEBUG = False
  3374. NORUN = False # If set, run() does nothing. Used by load_app()
  3375. #: A dict to map HTTP status codes (e.g. 404) to phrases (e.g. 'Not Found')
  3376. HTTP_CODES = httplib.responses
  3377. HTTP_CODES[418] = "I'm a teapot" # RFC 2324
  3378. HTTP_CODES[422] = "Unprocessable Entity" # RFC 4918
  3379. HTTP_CODES[428] = "Precondition Required"
  3380. HTTP_CODES[429] = "Too Many Requests"
  3381. HTTP_CODES[431] = "Request Header Fields Too Large"
  3382. HTTP_CODES[511] = "Network Authentication Required"
  3383. _HTTP_STATUS_LINES = dict((k, "%d %s" % (k, v)) for (k, v) in HTTP_CODES.items())
  3384. #: The default template used for error pages. Override with @error()
  3385. ERROR_PAGE_TEMPLATE = (
  3386. """
  3387. %%try:
  3388. %%from %s import DEBUG, HTTP_CODES, request, touni
  3389. <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
  3390. <html>
  3391. <head>
  3392. <title>Error: {{e.status}}</title>
  3393. <style type="text/css">
  3394. html {background-color: #eee; font-family: sans;}
  3395. body {background-color: #fff; border: 1px solid #ddd;
  3396. padding: 15px; margin: 15px;}
  3397. pre {background-color: #eee; border: 1px solid #ddd; padding: 5px;}
  3398. </style>
  3399. </head>
  3400. <body>
  3401. <h1>Error: {{e.status}}</h1>
  3402. <p>Sorry, the requested URL <tt>{{repr(request.url)}}</tt>
  3403. caused an error:</p>
  3404. <pre>{{e.body}}</pre>
  3405. %%if DEBUG and e.exception:
  3406. <h2>Exception:</h2>
  3407. <pre>{{repr(e.exception)}}</pre>
  3408. %%end
  3409. %%if DEBUG and e.traceback:
  3410. <h2>Traceback:</h2>
  3411. <pre>{{e.traceback}}</pre>
  3412. %%end
  3413. </body>
  3414. </html>
  3415. %%except ImportError:
  3416. <b>ImportError:</b> Could not generate the error page. Please add bottle to
  3417. the import path.
  3418. %%end
  3419. """
  3420. % __name__
  3421. )
  3422. #: A thread-safe instance of :class:`LocalRequest`. If accessed from within a
  3423. #: request callback, this instance always refers to the *current* request
  3424. #: (even on a multithreaded server).
  3425. request = LocalRequest()
  3426. #: A thread-safe instance of :class:`LocalResponse`. It is used to change the
  3427. #: HTTP response for the *current* request.
  3428. response = LocalResponse()
  3429. #: A thread-safe namespace. Not used by Bottle.
  3430. local = threading.local()
  3431. # Initialize app stack (create first empty Bottle app)
  3432. # BC: 0.6.4 and needed for run()
  3433. app = default_app = AppStack()
  3434. app.push()
  3435. #: A virtual package that redirects import statements.
  3436. #: Example: ``import bottle.ext.sqlite`` actually imports `bottle_sqlite`.
  3437. ext = _ImportRedirect(
  3438. "bottle.ext" if __name__ == "__main__" else __name__ + ".ext", "bottle_%s"
  3439. ).module
  3440. if __name__ == "__main__":
  3441. opt, args, parser = _cmd_options, _cmd_args, _cmd_parser
  3442. if opt.version:
  3443. _stdout("Bottle %s\n" % __version__)
  3444. sys.exit(0)
  3445. if not args:
  3446. parser.print_help()
  3447. _stderr("\nError: No application specified.\n")
  3448. sys.exit(1)
  3449. sys.path.insert(0, ".")
  3450. sys.modules.setdefault("bottle", sys.modules["__main__"])
  3451. host, port = (opt.bind or "localhost"), 8080
  3452. if ":" in host and host.rfind("]") < host.rfind(":"):
  3453. host, port = host.rsplit(":", 1)
  3454. host = host.strip("[]")
  3455. run(
  3456. args[0],
  3457. host=host,
  3458. port=int(port),
  3459. server=opt.server,
  3460. reloader=opt.reload,
  3461. plugins=opt.plugin,
  3462. debug=opt.debug,
  3463. )
  3464. # THE END