bottle.py 147 KB

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