Python module (submodule repositary), which provides content (video streams) from various online stream sources to corresponding Enigma2, Kodi, Plex plugins

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