bottle.py 141 KB

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