<s> """<STR_LIT>""" <EOL> from __future__ import with_statement <EOL> __author__ = '<STR_LIT>' <EOL> __version__ = '<STR_LIT>' <EOL> __license__ = '<STR_LIT>' <EOL> if __name__ == '<STR_LIT:__main__>' : <EOL> from optparse import OptionParser <EOL> _cmd_parser = OptionParser ( usage = "<STR_LIT>" ) <EOL> _opt = _cmd_parser . add_option <EOL> _opt ( "<STR_LIT>" , action = "<STR_LIT:store_true>" , help = "<STR_LIT>" ) <EOL> _opt ( "<STR_LIT>" , "<STR_LIT>" , metavar = "<STR_LIT>" , help = "<STR_LIT>" ) <EOL> _opt ( "<STR_LIT>" , "<STR_LIT>" , default = '<STR_LIT>' , help = "<STR_LIT>" ) <EOL> _opt ( "<STR_LIT>" , "<STR_LIT>" , action = "<STR_LIT>" , help = "<STR_LIT>" ) <EOL> _opt ( "<STR_LIT>" , action = "<STR_LIT:store_true>" , help = "<STR_LIT>" ) <EOL> _opt ( "<STR_LIT>" , action = "<STR_LIT:store_true>" , help = "<STR_LIT>" ) <EOL> _cmd_options , _cmd_args = _cmd_parser . parse_args ( ) <EOL> if _cmd_options . server and _cmd_options . server . startswith ( '<STR_LIT>' ) : <EOL> import gevent . monkey ; gevent . monkey . patch_all ( ) <EOL> import base64 , cgi , email . utils , functools , hmac , imp , itertools , mimetypes , os , re , subprocess , sys , tempfile , threading , time , urllib , warnings <EOL> from datetime import date as datedate , datetime , timedelta <EOL> from tempfile import TemporaryFile <EOL> from traceback import format_exc , print_exc <EOL> try : from json import dumps as json_dumps , loads as json_lds <EOL> except ImportError : <EOL> try : from simplejson import dumps as json_dumps , loads as json_lds <EOL> except ImportError : <EOL> try : from django . utils . simplejson import dumps as json_dumps , loads as json_lds <EOL> except ImportError : <EOL> def json_dumps ( data ) : <EOL> raise ImportError ( "<STR_LIT>" ) <EOL> json_lds = json_dumps <EOL> py = sys . version_info <EOL> py3k = py >= ( <NUM_LIT:3> , <NUM_LIT:0> , <NUM_LIT:0> ) <EOL> py25 = py < ( <NUM_LIT:2> , <NUM_LIT:6> , <NUM_LIT:0> ) <EOL> py31 = ( <NUM_LIT:3> , <NUM_LIT:1> , <NUM_LIT:0> ) <= py < ( <NUM_LIT:3> , <NUM_LIT:2> , <NUM_LIT:0> ) <EOL> def _e ( ) : return sys . exc_info ( ) [ <NUM_LIT:1> ] <EOL> try : <EOL> _stdout , _stderr = sys . stdout . write , sys . stderr . write <EOL> except IOError : <EOL> _stdout = lambda x : sys . stdout . write ( x ) <EOL> _stderr = lambda x : sys . stderr . write ( x ) <EOL> if py3k : <EOL> import http . client as httplib <EOL> import _thread as thread <EOL> from urllib . parse import urljoin , SplitResult as UrlSplitResult <EOL> from urllib . parse import urlencode , quote as urlquote , unquote as urlunquote <EOL> urlunquote = functools . partial ( urlunquote , encoding = '<STR_LIT>' ) <EOL> from http . cookies import SimpleCookie <EOL> from collections import MutableMapping as DictMixin <EOL> import pickle <EOL> from io import BytesIO <EOL> basestring = str <EOL> unicode = str <EOL> json_loads = lambda s : json_lds ( touni ( s ) ) <EOL> callable = lambda x : hasattr ( x , '<STR_LIT>' ) <EOL> imap = map <EOL> def _raise ( * a ) : raise a [ <NUM_LIT:0> ] ( a [ <NUM_LIT:1> ] ) . with_traceback ( a [ <NUM_LIT:2> ] ) <EOL> else : <EOL> import httplib <EOL> import thread <EOL> from urlparse import urljoin , SplitResult as UrlSplitResult <EOL> from urllib import urlencode , quote as urlquote , unquote as urlunquote <EOL> from Cookie import SimpleCookie <EOL> from itertools import imap <EOL> import cPickle as pickle <EOL> from StringIO import StringIO as BytesIO <EOL> if py25 : <EOL> msg = "<STR_LIT>" <EOL> warnings . warn ( msg , DeprecationWarning ) <EOL> from UserDict import DictMixin <EOL> def next ( it ) : return it . next ( ) <EOL> bytes = str <EOL> else : <EOL> from collections import MutableMapping as DictMixin <EOL> json_loads = json_lds <EOL> eval ( compile ( '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) ) <EOL> def tob ( s , enc = '<STR_LIT:utf8>' ) : <EOL> return s . encode ( enc ) if isinstance ( s , unicode ) else bytes ( s ) <EOL> def touni ( s , enc = '<STR_LIT:utf8>' , err = '<STR_LIT:strict>' ) : <EOL> return s . decode ( enc , err ) if isinstance ( s , bytes ) else unicode ( s ) <EOL> tonat = touni if py3k else tob <EOL> if py31 : <EOL> from io import TextIOWrapper <EOL> class NCTextIOWrapper ( TextIOWrapper ) : <EOL> def close ( self ) : pass <EOL> def update_wrapper ( wrapper , wrapped , * a , ** ka ) : <EOL> try : functools . update_wrapper ( wrapper , wrapped , * a , ** ka ) <EOL> except AttributeError : pass <EOL> def depr ( message , hard = False ) : <EOL> warnings . warn ( message , DeprecationWarning , stacklevel = <NUM_LIT:3> ) <EOL> def makelist ( data ) : <EOL> if isinstance ( data , ( tuple , list , set , dict ) ) : return list ( data ) <EOL> elif data : return [ data ] <EOL> else : return [ ] <EOL> class DictProperty ( object ) : <EOL> '''<STR_LIT>''' <EOL> def __init__ ( self , attr , key = None , read_only = False ) : <EOL> self . attr , self . key , self . read_only = attr , key , read_only <EOL> def __call__ ( self , func ) : <EOL> functools . update_wrapper ( self , func , updated = [ ] ) <EOL> self . getter , self . key = func , self . key or func . __name__ <EOL> return self <EOL> def __get__ ( self , obj , cls ) : <EOL> if obj is None : return self <EOL> key , storage = self . key , getattr ( obj , self . attr ) <EOL> if key not in storage : storage [ key ] = self . getter ( obj ) <EOL> return storage [ key ] <EOL> def __set__ ( self , obj , value ) : <EOL> if self . read_only : raise AttributeError ( "<STR_LIT>" ) <EOL> getattr ( obj , self . attr ) [ self . key ] = value <EOL> def __delete__ ( self , obj ) : <EOL> if self . read_only : raise AttributeError ( "<STR_LIT>" ) <EOL> del getattr ( obj , self . attr ) [ self . key ] <EOL> class cached_property ( object ) : <EOL> '''<STR_LIT>''' <EOL> def __init__ ( self , func ) : <EOL> self . __doc__ = getattr ( func , '<STR_LIT>' ) <EOL> self . func = func <EOL> def __get__ ( self , obj , cls ) : <EOL> if obj is None : return self <EOL> value = obj . __dict__ [ self . func . __name__ ] = self . func ( obj ) <EOL> return value <EOL> class lazy_attribute ( object ) : <EOL> '''<STR_LIT>''' <EOL> def __init__ ( self , func ) : <EOL> functools . update_wrapper ( self , func , updated = [ ] ) <EOL> self . getter = func <EOL> def __get__ ( self , obj , cls ) : <EOL> value = self . getter ( cls ) <EOL> setattr ( cls , self . __name__ , value ) <EOL> return value <EOL> class BottleException ( Exception ) : <EOL> """<STR_LIT>""" <EOL> pass <EOL> class RouteError ( BottleException ) : <EOL> """<STR_LIT>""" <EOL> class RouteReset ( BottleException ) : <EOL> """<STR_LIT>""" <EOL> class RouterUnknownModeError ( RouteError ) : pass <EOL> class RouteSyntaxError ( RouteError ) : <EOL> """<STR_LIT>""" <EOL> class RouteBuildError ( RouteError ) : <EOL> """<STR_LIT>""" <EOL> def _re_flatten ( p ) : <EOL> '''<STR_LIT>''' <EOL> if '<STR_LIT:(>' not in p : return p <EOL> return re . sub ( r'<STR_LIT>' , <EOL> lambda m : m . group ( <NUM_LIT:0> ) if len ( m . group ( <NUM_LIT:1> ) ) % <NUM_LIT:2> else m . group ( <NUM_LIT:1> ) + '<STR_LIT>' , p ) <EOL> class Router ( object ) : <EOL> '''<STR_LIT>''' <EOL> default_pattern = '<STR_LIT>' <EOL> default_filter = '<STR_LIT>' <EOL> def __init__ ( self , strict = False ) : <EOL> self . rules = [ ] <EOL> self . _groups = { } <EOL> self . builder = { } <EOL> self . static = { } <EOL> self . dynamic = [ ] <EOL> self . strict_order = strict <EOL> self . filters = { <EOL> '<STR_LIT>' : lambda conf : <EOL> ( _re_flatten ( conf or self . default_pattern ) , None , None ) , <EOL> '<STR_LIT:int>' : lambda conf : ( r'<STR_LIT>' , int , lambda x : str ( int ( x ) ) ) , <EOL> '<STR_LIT:float>' : lambda conf : ( r'<STR_LIT>' , float , lambda x : str ( float ( x ) ) ) , <EOL> '<STR_LIT:path>' : lambda conf : ( r'<STR_LIT>' , None , None ) } <EOL> def add_filter ( self , name , func ) : <EOL> '''<STR_LIT>''' <EOL> self . filters [ name ] = func <EOL> rule_syntax = re . compile ( '<STR_LIT>' '<STR_LIT>' '<STR_LIT>' '<STR_LIT>' ) <EOL> def _itertokens ( self , rule ) : <EOL> offset , prefix = <NUM_LIT:0> , '<STR_LIT>' <EOL> for match in self . rule_syntax . finditer ( rule ) : <EOL> prefix += rule [ offset : match . start ( ) ] <EOL> g = match . groups ( ) <EOL> if len ( g [ <NUM_LIT:0> ] ) % <NUM_LIT:2> : <EOL> prefix += match . group ( <NUM_LIT:0> ) [ len ( g [ <NUM_LIT:0> ] ) : ] <EOL> offset = match . end ( ) <EOL> continue <EOL> if prefix : <EOL> yield prefix , None , None <EOL> name , filtr , conf = g [ <NUM_LIT:4> : <NUM_LIT:7> ] if g [ <NUM_LIT:2> ] is None else g [ <NUM_LIT:1> : <NUM_LIT:4> ] <EOL> yield name , filtr or '<STR_LIT:default>' , conf or None <EOL> offset , prefix = match . end ( ) , '<STR_LIT>' <EOL> if offset <= len ( rule ) or prefix : <EOL> yield prefix + rule [ offset : ] , None , None <EOL> def add ( self , rule , method , target , name = None ) : <EOL> '''<STR_LIT>''' <EOL> anons = <NUM_LIT:0> <EOL> keys = [ ] <EOL> pattern = '<STR_LIT>' <EOL> filters = [ ] <EOL> builder = [ ] <EOL> is_static = True <EOL> for key , mode , conf in self . _itertokens ( rule ) : <EOL> if mode : <EOL> is_static = False <EOL> if mode == '<STR_LIT:default>' : mode = self . default_filter <EOL> mask , in_filter , out_filter = self . filters [ mode ] ( conf ) <EOL> if not key : <EOL> pattern += '<STR_LIT>' % mask <EOL> key = '<STR_LIT>' % anons <EOL> anons += <NUM_LIT:1> <EOL> else : <EOL> pattern += '<STR_LIT>' % ( key , mask ) <EOL> keys . append ( key ) <EOL> if in_filter : filters . append ( ( key , in_filter ) ) <EOL> builder . append ( ( key , out_filter or str ) ) <EOL> elif key : <EOL> pattern += re . escape ( key ) <EOL> builder . append ( ( None , key ) ) <EOL> self . builder [ rule ] = builder <EOL> if name : self . builder [ name ] = builder <EOL> if is_static and not self . strict_order : <EOL> group = self . static . setdefault ( self . build ( rule ) , { } ) <EOL> group [ method ] = ( target , None ) <EOL> return <EOL> try : <EOL> re_pattern = re . compile ( '<STR_LIT>' % pattern ) <EOL> re_match = re_pattern . match <EOL> except re . error : <EOL> raise RouteSyntaxError ( "<STR_LIT>" % ( rule , _e ( ) ) ) <EOL> if filters : <EOL> def getargs ( path ) : <EOL> url_args = re_match ( path ) . groupdict ( ) <EOL> for name , wildcard_filter in filters : <EOL> try : <EOL> url_args [ name ] = wildcard_filter ( url_args [ name ] ) <EOL> except ValueError : <EOL> raise HTTPError ( <NUM_LIT> , '<STR_LIT>' ) <EOL> return url_args <EOL> elif re_pattern . groupindex : <EOL> def getargs ( path ) : <EOL> return re_match ( path ) . groupdict ( ) <EOL> else : <EOL> getargs = None <EOL> flatpat = _re_flatten ( pattern ) <EOL> if flatpat in self . _groups : <EOL> group = self . _groups [ flatpat ] <EOL> if method in group : <EOL> if DEBUG : <EOL> msg = '<STR_LIT>' <EOL> warnings . warn ( msg % ( method , rule ) , RuntimeWarning ) <EOL> self . _groups [ flatpat ] [ method ] = ( target , getargs ) <EOL> return <EOL> mdict = self . _groups [ flatpat ] = { method : ( target , getargs ) } <EOL> try : <EOL> combined = '<STR_LIT>' % ( self . dynamic [ - <NUM_LIT:1> ] [ <NUM_LIT:0> ] . pattern , flatpat ) <EOL> self . dynamic [ - <NUM_LIT:1> ] = ( re . compile ( combined ) , self . dynamic [ - <NUM_LIT:1> ] [ <NUM_LIT:1> ] ) <EOL> self . dynamic [ - <NUM_LIT:1> ] [ <NUM_LIT:1> ] . append ( mdict ) <EOL> except ( AssertionError , IndexError ) : <EOL> self . dynamic . append ( ( re . compile ( '<STR_LIT>' % flatpat ) , [ mdict ] ) ) <EOL> def build ( self , _name , * anons , ** query ) : <EOL> '''<STR_LIT>''' <EOL> builder = self . builder . get ( _name ) <EOL> if not builder : raise RouteBuildError ( "<STR_LIT>" , _name ) <EOL> try : <EOL> for i , value in enumerate ( anons ) : query [ '<STR_LIT>' % i ] = value <EOL> url = '<STR_LIT>' . join ( [ f ( query . pop ( n ) ) if n else f for ( n , f ) in builder ] ) <EOL> return url if not query else url + '<STR_LIT:?>' + urlencode ( query ) <EOL> except KeyError : <EOL> raise RouteBuildError ( '<STR_LIT>' % _e ( ) . args [ <NUM_LIT:0> ] ) <EOL> def match ( self , environ ) : <EOL> '''<STR_LIT>''' <EOL> path , targets , urlargs = environ [ '<STR_LIT>' ] or '<STR_LIT:/>' , None , { } <EOL> if path in self . static : <EOL> targets = self . static [ path ] <EOL> else : <EOL> for combined , rules in self . dynamic : <EOL> match = combined . match ( path ) <EOL> if not match : continue <EOL> targets = rules [ match . lastindex - <NUM_LIT:1> ] <EOL> break <EOL> if not targets : <EOL> raise HTTPError ( <NUM_LIT> , "<STR_LIT>" + repr ( environ [ '<STR_LIT>' ] ) ) <EOL> method = environ [ '<STR_LIT>' ] . upper ( ) <EOL> if method in targets : <EOL> target , getargs = targets [ method ] <EOL> elif method == '<STR_LIT>' and '<STR_LIT:GET>' in targets : <EOL> target , getargs = targets [ '<STR_LIT:GET>' ] <EOL> elif '<STR_LIT>' in targets : <EOL> target , getargs = targets [ '<STR_LIT>' ] <EOL> else : <EOL> allowed = [ verb for verb in targets if verb != '<STR_LIT>' ] <EOL> if '<STR_LIT:GET>' in allowed and '<STR_LIT>' not in allowed : <EOL> allowed . append ( '<STR_LIT>' ) <EOL> raise HTTPError ( <NUM_LIT> , "<STR_LIT>" , Allow = "<STR_LIT:U+002C>" . join ( allowed ) ) <EOL> return target , getargs ( path ) if getargs else { } <EOL> class Route ( object ) : <EOL> '''<STR_LIT>''' <EOL> def __init__ ( self , app , rule , method , callback , name = None , <EOL> plugins = None , skiplist = None , ** config ) : <EOL> self . app = app <EOL> self . rule = rule <EOL> self . method = method <EOL> self . callback = callback <EOL> self . name = name or None <EOL> self . plugins = plugins or [ ] <EOL> self . skiplist = skiplist or [ ] <EOL> self . config = ConfigDict ( config ) <EOL> def __call__ ( self , * a , ** ka ) : <EOL> depr ( "<STR_LIT>" "<STR_LIT>" "<STR_LIT>" ) <EOL> return self . call ( * a , ** ka ) <EOL> @ cached_property <EOL> def call ( self ) : <EOL> '''<STR_LIT>''' <EOL> return self . _make_callback ( ) <EOL> def reset ( self ) : <EOL> '''<STR_LIT>''' <EOL> self . __dict__ . pop ( '<STR_LIT>' , None ) <EOL> def prepare ( self ) : <EOL> '''<STR_LIT>''' <EOL> self . call <EOL> @ property <EOL> def _context ( self ) : <EOL> depr ( '<STR_LIT>' ) <EOL> return dict ( rule = self . rule , method = self . method , callback = self . callback , <EOL> name = self . name , app = self . app , config = self . config , <EOL> apply = self . plugins , skip = self . skiplist ) <EOL> def all_plugins ( self ) : <EOL> '''<STR_LIT>''' <EOL> unique = set ( ) <EOL> for p in reversed ( self . app . plugins + self . plugins ) : <EOL> if True in self . skiplist : break <EOL> name = getattr ( p , '<STR_LIT:name>' , False ) <EOL> if name and ( name in self . skiplist or name in unique ) : continue <EOL> if p in self . skiplist or type ( p ) in self . skiplist : continue <EOL> if name : unique . add ( name ) <EOL> yield p <EOL> def _make_callback ( self ) : <EOL> callback = self . callback <EOL> for plugin in self . all_plugins ( ) : <EOL> try : <EOL> if hasattr ( plugin , '<STR_LIT>' ) : <EOL> api = getattr ( plugin , '<STR_LIT>' , <NUM_LIT:1> ) <EOL> context = self if api > <NUM_LIT:1> else self . _context <EOL> callback = plugin . apply ( callback , context ) <EOL> else : <EOL> callback = plugin ( callback ) <EOL> except RouteReset : <EOL> return self . _make_callback ( ) <EOL> if not callback is self . callback : <EOL> update_wrapper ( callback , self . callback ) <EOL> return callback <EOL> def __repr__ ( self ) : <EOL> return '<STR_LIT>' % ( self . method , self . rule , self . callback ) <EOL> class Bottle ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , catchall = True , autojson = True ) : <EOL> self . catchall = catchall <EOL> self . resources = ResourceManager ( ) <EOL> self . config = ConfigDict ( ) <EOL> self . config . autojson = autojson <EOL> self . routes = [ ] <EOL> self . router = Router ( ) <EOL> self . error_handler = { } <EOL> self . plugins = [ ] <EOL> self . hooks = HooksPlugin ( ) <EOL> self . install ( self . hooks ) <EOL> if self . config . autojson : <EOL> self . install ( JSONPlugin ( ) ) <EOL> self . install ( TemplatePlugin ( ) ) <EOL> def mount ( self , prefix , app , ** options ) : <EOL> '''<STR_LIT>''' <EOL> if isinstance ( app , basestring ) : <EOL> depr ( '<STR_LIT>' , True ) <EOL> segments = [ p for p in prefix . split ( '<STR_LIT:/>' ) if p ] <EOL> if not segments : raise ValueError ( '<STR_LIT>' ) <EOL> path_depth = len ( segments ) <EOL> def mountpoint_wrapper ( ) : <EOL> try : <EOL> request . path_shift ( path_depth ) <EOL> rs = HTTPResponse ( [ ] ) <EOL> def start_response ( status , headerlist , exc_info = None ) : <EOL> if exc_info : <EOL> try : <EOL> _raise ( * exc_info ) <EOL> finally : <EOL> exc_info = None <EOL> rs . status = status <EOL> for name , value in headerlist : rs . add_header ( name , value ) <EOL> return rs . body . append <EOL> body = app ( request . environ , start_response ) <EOL> if body and rs . body : body = itertools . chain ( rs . body , body ) <EOL> rs . body = body or rs . body <EOL> return rs <EOL> finally : <EOL> request . path_shift ( - path_depth ) <EOL> options . setdefault ( '<STR_LIT>' , True ) <EOL> options . setdefault ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> options . setdefault ( '<STR_LIT>' , { '<STR_LIT>' : prefix , '<STR_LIT:target>' : app } ) <EOL> options [ '<STR_LIT>' ] = mountpoint_wrapper <EOL> self . route ( '<STR_LIT>' % '<STR_LIT:/>' . join ( segments ) , ** options ) <EOL> if not prefix . endswith ( '<STR_LIT:/>' ) : <EOL> self . route ( '<STR_LIT:/>' + '<STR_LIT:/>' . join ( segments ) , ** options ) <EOL> def merge ( self , routes ) : <EOL> '''<STR_LIT>''' <EOL> if isinstance ( routes , Bottle ) : <EOL> routes = routes . routes <EOL> for route in routes : <EOL> self . add_route ( route ) <EOL> def install ( self , plugin ) : <EOL> '''<STR_LIT>''' <EOL> if hasattr ( plugin , '<STR_LIT>' ) : plugin . setup ( self ) <EOL> if not callable ( plugin ) and not hasattr ( plugin , '<STR_LIT>' ) : <EOL> raise TypeError ( "<STR_LIT>" ) <EOL> self . plugins . append ( plugin ) <EOL> self . reset ( ) <EOL> return plugin <EOL> def uninstall ( self , plugin ) : <EOL> '''<STR_LIT>''' <EOL> removed , remove = [ ] , plugin <EOL> for i , plugin in list ( enumerate ( self . plugins ) ) [ : : - <NUM_LIT:1> ] : <EOL> if remove is True or remove is plugin or remove is type ( plugin ) or getattr ( plugin , '<STR_LIT:name>' , True ) == remove : <EOL> removed . append ( plugin ) <EOL> del self . plugins [ i ] <EOL> if hasattr ( plugin , '<STR_LIT>' ) : plugin . close ( ) <EOL> if removed : self . reset ( ) <EOL> return removed <EOL> def run ( self , ** kwargs ) : <EOL> '''<STR_LIT>''' <EOL> run ( self , ** kwargs ) <EOL> def reset ( self , route = None ) : <EOL> '''<STR_LIT>''' <EOL> if route is None : routes = self . routes <EOL> elif isinstance ( route , Route ) : routes = [ route ] <EOL> else : routes = [ self . routes [ route ] ] <EOL> for route in routes : route . reset ( ) <EOL> if DEBUG : <EOL> for route in routes : route . prepare ( ) <EOL> self . hooks . trigger ( '<STR_LIT>' ) <EOL> def close ( self ) : <EOL> '''<STR_LIT>''' <EOL> for plugin in self . plugins : <EOL> if hasattr ( plugin , '<STR_LIT>' ) : plugin . close ( ) <EOL> self . stopped = True <EOL> def match ( self , environ ) : <EOL> """<STR_LIT>""" <EOL> return self . router . match ( environ ) <EOL> def get_url ( self , routename , ** kargs ) : <EOL> """<STR_LIT>""" <EOL> scriptname = request . environ . get ( '<STR_LIT>' , '<STR_LIT>' ) . strip ( '<STR_LIT:/>' ) + '<STR_LIT:/>' <EOL> location = self . router . build ( routename , ** kargs ) . lstrip ( '<STR_LIT:/>' ) <EOL> return urljoin ( urljoin ( '<STR_LIT:/>' , scriptname ) , location ) <EOL> def add_route ( self , route ) : <EOL> '''<STR_LIT>''' <EOL> self . routes . append ( route ) <EOL> self . router . add ( route . rule , route . method , route , name = route . name ) <EOL> if DEBUG : route . prepare ( ) <EOL> def route ( self , path = None , method = '<STR_LIT:GET>' , callback = None , name = None , <EOL> apply = None , skip = None , ** config ) : <EOL> """<STR_LIT>""" <EOL> if callable ( path ) : path , callback = None , path <EOL> plugins = makelist ( apply ) <EOL> skiplist = makelist ( skip ) <EOL> def decorator ( callback ) : <EOL> if isinstance ( callback , basestring ) : callback = load ( callback ) <EOL> for rule in makelist ( path ) or yieldroutes ( callback ) : <EOL> for verb in makelist ( method ) : <EOL> verb = verb . upper ( ) <EOL> route = Route ( self , rule , verb , callback , name = name , <EOL> plugins = plugins , skiplist = skiplist , ** config ) <EOL> self . add_route ( route ) <EOL> return callback <EOL> return decorator ( callback ) if callback else decorator <EOL> def get ( self , path = None , method = '<STR_LIT:GET>' , ** options ) : <EOL> """<STR_LIT>""" <EOL> return self . route ( path , method , ** options ) <EOL> def post ( self , path = None , method = '<STR_LIT:POST>' , ** options ) : <EOL> """<STR_LIT>""" <EOL> return self . route ( path , method , ** options ) <EOL> def put ( self , path = None , method = '<STR_LIT>' , ** options ) : <EOL> """<STR_LIT>""" <EOL> return self . route ( path , method , ** options ) <EOL> def delete ( self , path = None , method = '<STR_LIT>' , ** options ) : <EOL> """<STR_LIT>""" <EOL> return self . route ( path , method , ** options ) <EOL> def error ( self , code = <NUM_LIT> ) : <EOL> """<STR_LIT>""" <EOL> def wrapper ( handler ) : <EOL> self . error_handler [ int ( code ) ] = handler <EOL> return handler <EOL> return wrapper <EOL> def hook ( self , name ) : <EOL> """<STR_LIT>""" <EOL> def wrapper ( func ) : <EOL> self . hooks . add ( name , func ) <EOL> return func <EOL> return wrapper <EOL> def handle ( self , path , method = '<STR_LIT:GET>' ) : <EOL> """<STR_LIT>""" <EOL> depr ( "<STR_LIT>" ) <EOL> if isinstance ( path , dict ) : <EOL> return self . _handle ( path ) <EOL> return self . _handle ( { '<STR_LIT>' : path , '<STR_LIT>' : method . upper ( ) } ) <EOL> def default_error_handler ( self , res ) : <EOL> return tob ( template ( ERROR_PAGE_TEMPLATE , e = res ) ) <EOL> def _handle ( self , environ ) : <EOL> try : <EOL> environ [ '<STR_LIT>' ] = self <EOL> request . bind ( environ ) <EOL> response . bind ( ) <EOL> route , args = self . router . match ( environ ) <EOL> environ [ '<STR_LIT>' ] = route <EOL> environ [ '<STR_LIT>' ] = route <EOL> environ [ '<STR_LIT>' ] = args <EOL> return route . call ( ** args ) <EOL> except HTTPResponse : <EOL> return _e ( ) <EOL> except RouteReset : <EOL> route . reset ( ) <EOL> return self . _handle ( environ ) <EOL> except ( KeyboardInterrupt , SystemExit , MemoryError ) : <EOL> raise <EOL> except Exception : <EOL> if not self . catchall : raise <EOL> stacktrace = format_exc ( ) <EOL> environ [ '<STR_LIT>' ] . write ( stacktrace ) <EOL> return HTTPError ( <NUM_LIT> , "<STR_LIT>" , _e ( ) , stacktrace ) <EOL> def _cast ( self , out , peek = None ) : <EOL> """<STR_LIT>""" <EOL> if not out : <EOL> if '<STR_LIT>' not in response : <EOL> response [ '<STR_LIT>' ] = <NUM_LIT:0> <EOL> return [ ] <EOL> if isinstance ( out , ( tuple , list ) ) and isinstance ( out [ <NUM_LIT:0> ] , ( bytes , unicode ) ) : <EOL> out = out [ <NUM_LIT:0> ] [ <NUM_LIT:0> : <NUM_LIT:0> ] . join ( out ) <EOL> if isinstance ( out , unicode ) : <EOL> out = out . encode ( response . charset ) <EOL> if isinstance ( out , bytes ) : <EOL> if '<STR_LIT>' not in response : <EOL> response [ '<STR_LIT>' ] = len ( out ) <EOL> return [ out ] <EOL> if isinstance ( out , HTTPError ) : <EOL> out . apply ( response ) <EOL> out = self . error_handler . get ( out . status_code , self . default_error_handler ) ( out ) <EOL> return self . _cast ( out ) <EOL> if isinstance ( out , HTTPResponse ) : <EOL> out . apply ( response ) <EOL> return self . _cast ( out . body ) <EOL> if hasattr ( out , '<STR_LIT>' ) : <EOL> if '<STR_LIT>' in request . environ : <EOL> return request . environ [ '<STR_LIT>' ] ( out ) <EOL> elif hasattr ( out , '<STR_LIT>' ) or not hasattr ( out , '<STR_LIT>' ) : <EOL> return WSGIFileWrapper ( out ) <EOL> try : <EOL> iout = iter ( out ) <EOL> first = next ( iout ) <EOL> while not first : <EOL> first = next ( iout ) <EOL> except StopIteration : <EOL> return self . _cast ( '<STR_LIT>' ) <EOL> except HTTPResponse : <EOL> first = _e ( ) <EOL> except ( KeyboardInterrupt , SystemExit , MemoryError ) : <EOL> raise <EOL> except Exception : <EOL> if not self . catchall : raise <EOL> first = HTTPError ( <NUM_LIT> , '<STR_LIT>' , _e ( ) , format_exc ( ) ) <EOL> if isinstance ( first , HTTPResponse ) : <EOL> return self . _cast ( first ) <EOL> elif isinstance ( first , bytes ) : <EOL> new_iter = itertools . chain ( [ first ] , iout ) <EOL> elif isinstance ( first , unicode ) : <EOL> encoder = lambda x : x . encode ( response . charset ) <EOL> new_iter = imap ( encoder , itertools . chain ( [ first ] , iout ) ) <EOL> else : <EOL> msg = '<STR_LIT>' % type ( first ) <EOL> return self . _cast ( HTTPError ( <NUM_LIT> , msg ) ) <EOL> if hasattr ( out , '<STR_LIT>' ) : <EOL> new_iter = _closeiter ( new_iter , out . close ) <EOL> return new_iter <EOL> def wsgi ( self , environ , start_response ) : <EOL> """<STR_LIT>""" <EOL> try : <EOL> out = self . _cast ( self . _handle ( environ ) ) <EOL> if response . _status_code in ( <NUM_LIT:100> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> ) or environ [ '<STR_LIT>' ] == '<STR_LIT>' : <EOL> if hasattr ( out , '<STR_LIT>' ) : out . close ( ) <EOL> out = [ ] <EOL> start_response ( response . _status_line , response . headerlist ) <EOL> return out <EOL> except ( KeyboardInterrupt , SystemExit , MemoryError ) : <EOL> raise <EOL> except Exception : <EOL> if not self . catchall : raise <EOL> err = '<STR_LIT>' % html_escape ( environ . get ( '<STR_LIT>' , '<STR_LIT:/>' ) ) <EOL> if DEBUG : <EOL> err += '<STR_LIT>' '<STR_LIT>' % ( html_escape ( repr ( _e ( ) ) ) , html_escape ( format_exc ( ) ) ) <EOL> environ [ '<STR_LIT>' ] . write ( err ) <EOL> headers = [ ( '<STR_LIT:Content-Type>' , '<STR_LIT>' ) ] <EOL> start_response ( '<STR_LIT>' , headers , sys . exc_info ( ) ) <EOL> return [ tob ( err ) ] <EOL> def __call__ ( self , environ , start_response ) : <EOL> '''<STR_LIT>''' <EOL> return self . wsgi ( environ , start_response ) <EOL> class BaseRequest ( object ) : <EOL> """<STR_LIT>""" <EOL> __slots__ = ( '<STR_LIT>' ) <EOL> MEMFILE_MAX = <NUM_LIT> <EOL> MAX_PARAMS = <NUM_LIT:100> <EOL> def __init__ ( self , environ = None ) : <EOL> """<STR_LIT>""" <EOL> self . environ = { } if environ is None else environ <EOL> self . environ [ '<STR_LIT>' ] = self <EOL> @ DictProperty ( '<STR_LIT>' , '<STR_LIT>' , read_only = True ) <EOL> def app ( self ) : <EOL> '''<STR_LIT>''' <EOL> raise RuntimeError ( '<STR_LIT>' ) <EOL> @ DictProperty ( '<STR_LIT>' , '<STR_LIT>' , read_only = True ) <EOL> def route ( self ) : <EOL> """<STR_LIT>""" <EOL> raise RuntimeError ( '<STR_LIT>' ) <EOL> @ DictProperty ( '<STR_LIT>' , '<STR_LIT>' , read_only = True ) <EOL> def url_args ( self ) : <EOL> """<STR_LIT>""" <EOL> raise RuntimeError ( '<STR_LIT>' ) <EOL> @ property <EOL> def path ( self ) : <EOL> '''<STR_LIT>''' <EOL> return '<STR_LIT:/>' + self . environ . get ( '<STR_LIT>' , '<STR_LIT>' ) . lstrip ( '<STR_LIT:/>' ) <EOL> @ property <EOL> def method ( self ) : <EOL> '''<STR_LIT>''' <EOL> return self . environ . get ( '<STR_LIT>' , '<STR_LIT:GET>' ) . upper ( ) <EOL> @ DictProperty ( '<STR_LIT>' , '<STR_LIT>' , read_only = True ) <EOL> def headers ( self ) : <EOL> '''<STR_LIT>''' <EOL> return WSGIHeaderDict ( self . environ ) <EOL> def get_header ( self , name , default = None ) : <EOL> '''<STR_LIT>''' <EOL> return self . headers . get ( name , default ) <EOL> @ DictProperty ( '<STR_LIT>' , '<STR_LIT>' , read_only = True ) <EOL> def cookies ( self ) : <EOL> """<STR_LIT>""" <EOL> cookies = SimpleCookie ( self . environ . get ( '<STR_LIT>' , '<STR_LIT>' ) ) . values ( ) <EOL> if len ( cookies ) > self . MAX_PARAMS : <EOL> raise HTTPError ( <NUM_LIT> , '<STR_LIT>' ) <EOL> return FormsDict ( ( c . key , c . value ) for c in cookies ) <EOL> def get_cookie ( self , key , default = None , secret = None ) : <EOL> """<STR_LIT>""" <EOL> value = self . cookies . get ( key ) <EOL> if secret and value : <EOL> dec = cookie_decode ( value , secret ) <EOL> return dec [ <NUM_LIT:1> ] if dec and dec [ <NUM_LIT:0> ] == key else default <EOL> return value or default <EOL> @ DictProperty ( '<STR_LIT>' , '<STR_LIT>' , read_only = True ) <EOL> def query ( self ) : <EOL> '''<STR_LIT>''' <EOL> get = self . environ [ '<STR_LIT>' ] = FormsDict ( ) <EOL> pairs = _parse_qsl ( self . environ . get ( '<STR_LIT>' , '<STR_LIT>' ) ) <EOL> if len ( pairs ) > self . MAX_PARAMS : <EOL> raise HTTPError ( <NUM_LIT> , '<STR_LIT>' ) <EOL> for key , value in pairs : <EOL> get [ key ] = value <EOL> return get <EOL> @ DictProperty ( '<STR_LIT>' , '<STR_LIT>' , read_only = True ) <EOL> def forms ( self ) : <EOL> """<STR_LIT>""" <EOL> forms = FormsDict ( ) <EOL> for name , item in self . POST . allitems ( ) : <EOL> if not isinstance ( item , FileUpload ) : <EOL> forms [ name ] = item <EOL> return forms <EOL> @ DictProperty ( '<STR_LIT>' , '<STR_LIT>' , read_only = True ) <EOL> def params ( self ) : <EOL> """<STR_LIT>""" <EOL> params = FormsDict ( ) <EOL> for key , value in self . query . allitems ( ) : <EOL> params [ key ] = value <EOL> for key , value in self . forms . allitems ( ) : <EOL> params [ key ] = value <EOL> return params <EOL> @ DictProperty ( '<STR_LIT>' , '<STR_LIT>' , read_only = True ) <EOL> def files ( self ) : <EOL> """<STR_LIT>""" <EOL> files = FormsDict ( ) <EOL> for name , item in self . POST . allitems ( ) : <EOL> if isinstance ( item , FileUpload ) : <EOL> files [ name ] = item <EOL> return files <EOL> @ DictProperty ( '<STR_LIT>' , '<STR_LIT>' , read_only = True ) <EOL> def json ( self ) : <EOL> '''<STR_LIT>''' <EOL> if '<STR_LIT:application/json>' in self . environ . get ( '<STR_LIT>' , '<STR_LIT>' ) : <EOL> return json_loads ( self . _get_body_string ( ) ) <EOL> return None <EOL> @ DictProperty ( '<STR_LIT>' , '<STR_LIT>' , read_only = True ) <EOL> def _body ( self ) : <EOL> maxread = max ( <NUM_LIT:0> , self . content_length ) <EOL> stream = self . environ [ '<STR_LIT>' ] <EOL> body = BytesIO ( ) if maxread < self . MEMFILE_MAX else TemporaryFile ( mode = '<STR_LIT>' ) <EOL> while maxread > <NUM_LIT:0> : <EOL> part = stream . read ( min ( maxread , self . MEMFILE_MAX ) ) <EOL> if not part : break <EOL> body . write ( part ) <EOL> maxread -= len ( part ) <EOL> self . environ [ '<STR_LIT>' ] = body <EOL> body . seek ( <NUM_LIT:0> ) <EOL> return body <EOL> def _get_body_string ( self ) : <EOL> '''<STR_LIT>''' <EOL> clen = self . content_length <EOL> if clen > self . MEMFILE_MAX : <EOL> raise HTTPError ( <NUM_LIT> , '<STR_LIT>' ) <EOL> if clen < <NUM_LIT:0> : clen = self . MEMFILE_MAX + <NUM_LIT:1> <EOL> data = self . body . read ( clen ) <EOL> if len ( data ) > self . MEMFILE_MAX : <EOL> raise HTTPError ( <NUM_LIT> , '<STR_LIT>' ) <EOL> return data <EOL> @ property <EOL> def body ( self ) : <EOL> """<STR_LIT>""" <EOL> self . _body . seek ( <NUM_LIT:0> ) <EOL> return self . _body <EOL> GET = query <EOL> @ DictProperty ( '<STR_LIT>' , '<STR_LIT>' , read_only = True ) <EOL> def POST ( self ) : <EOL> """<STR_LIT>""" <EOL> post = FormsDict ( ) <EOL> if not self . content_type . startswith ( '<STR_LIT>' ) : <EOL> pairs = _parse_qsl ( tonat ( self . _get_body_string ( ) , '<STR_LIT>' ) ) <EOL> if len ( pairs ) > self . MAX_PARAMS : <EOL> raise HTTPError ( <NUM_LIT> , '<STR_LIT>' ) <EOL> for key , value in pairs : <EOL> post [ key ] = value <EOL> return post <EOL> safe_env = { '<STR_LIT>' : '<STR_LIT>' } <EOL> for key in ( '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) : <EOL> if key in self . environ : safe_env [ key ] = self . environ [ key ] <EOL> args = dict ( fp = self . body , environ = safe_env , keep_blank_values = True ) <EOL> if py31 : <EOL> args [ '<STR_LIT>' ] = NCTextIOWrapper ( args [ '<STR_LIT>' ] , encoding = '<STR_LIT>' , <EOL> newline = '<STR_LIT:\n>' ) <EOL> elif py3k : <EOL> args [ '<STR_LIT>' ] = '<STR_LIT>' <EOL> data = cgi . FieldStorage ( ** args ) <EOL> data = data . list or [ ] <EOL> if len ( data ) > self . MAX_PARAMS : <EOL> raise HTTPError ( <NUM_LIT> , '<STR_LIT>' ) <EOL> for item in data : <EOL> if item . filename : <EOL> post [ item . name ] = FileUpload ( item . file , item . name , <EOL> item . filename , item . headers ) <EOL> else : <EOL> post [ item . name ] = item . value <EOL> return post <EOL> @ property <EOL> def COOKIES ( self ) : <EOL> '''<STR_LIT>''' <EOL> depr ( '<STR_LIT>' ) <EOL> return self . cookies <EOL> @ property <EOL> def url ( self ) : <EOL> """<STR_LIT>""" <EOL> return self . urlparts . geturl ( ) <EOL> @ DictProperty ( '<STR_LIT>' , '<STR_LIT>' , read_only = True ) <EOL> def urlparts ( self ) : <EOL> '''<STR_LIT>''' <EOL> env = self . environ <EOL> http = env . get ( '<STR_LIT>' ) or env . get ( '<STR_LIT>' , '<STR_LIT:http>' ) <EOL> host = env . get ( '<STR_LIT>' ) or env . get ( '<STR_LIT>' ) <EOL> if not host : <EOL> host = env . get ( '<STR_LIT>' , '<STR_LIT:127.0.0.1>' ) <EOL> port = env . get ( '<STR_LIT>' ) <EOL> if port and port != ( '<STR_LIT>' if http == '<STR_LIT:http>' else '<STR_LIT>' ) : <EOL> host += '<STR_LIT::>' + port <EOL> path = urlquote ( self . fullpath ) <EOL> return UrlSplitResult ( http , host , path , env . get ( '<STR_LIT>' ) , '<STR_LIT>' ) <EOL> @ property <EOL> def fullpath ( self ) : <EOL> """<STR_LIT>""" <EOL> return urljoin ( self . script_name , self . path . lstrip ( '<STR_LIT:/>' ) ) <EOL> @ property <EOL> def query_string ( self ) : <EOL> """<STR_LIT>""" <EOL> return self . environ . get ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> @ property <EOL> def script_name ( self ) : <EOL> '''<STR_LIT>''' <EOL> script_name = self . environ . get ( '<STR_LIT>' , '<STR_LIT>' ) . strip ( '<STR_LIT:/>' ) <EOL> return '<STR_LIT:/>' + script_name + '<STR_LIT:/>' if script_name else '<STR_LIT:/>' <EOL> def path_shift ( self , shift = <NUM_LIT:1> ) : <EOL> '''<STR_LIT>''' <EOL> script = self . environ . get ( '<STR_LIT>' , '<STR_LIT:/>' ) <EOL> self [ '<STR_LIT>' ] , self [ '<STR_LIT>' ] = path_shift ( script , self . path , shift ) <EOL> @ property <EOL> def content_length ( self ) : <EOL> '''<STR_LIT>''' <EOL> return int ( self . environ . get ( '<STR_LIT>' ) or - <NUM_LIT:1> ) <EOL> @ property <EOL> def content_type ( self ) : <EOL> '''<STR_LIT>''' <EOL> return self . environ . get ( '<STR_LIT>' , '<STR_LIT>' ) . lower ( ) <EOL> @ property <EOL> def is_xhr ( self ) : <EOL> '''<STR_LIT>''' <EOL> requested_with = self . environ . get ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> return requested_with . lower ( ) == '<STR_LIT>' <EOL> @ property <EOL> def is_ajax ( self ) : <EOL> '''<STR_LIT>''' <EOL> return self . is_xhr <EOL> @ property <EOL> def auth ( self ) : <EOL> """<STR_LIT>""" <EOL> basic = parse_auth ( self . environ . get ( '<STR_LIT>' , '<STR_LIT>' ) ) <EOL> if basic : return basic <EOL> ruser = self . environ . get ( '<STR_LIT>' ) <EOL> if ruser : return ( ruser , None ) <EOL> return None <EOL> @ property <EOL> def remote_route ( self ) : <EOL> """<STR_LIT>""" <EOL> proxy = self . environ . get ( '<STR_LIT>' ) <EOL> if proxy : return [ ip . strip ( ) for ip in proxy . split ( '<STR_LIT:U+002C>' ) ] <EOL> remote = self . environ . get ( '<STR_LIT>' ) <EOL> return [ remote ] if remote else [ ] <EOL> @ property <EOL> def remote_addr ( self ) : <EOL> """<STR_LIT>""" <EOL> route = self . remote_route <EOL> return route [ <NUM_LIT:0> ] if route else None <EOL> def copy ( self ) : <EOL> """<STR_LIT>""" <EOL> return Request ( self . environ . copy ( ) ) <EOL> def get ( self , value , default = None ) : return self . environ . get ( value , default ) <EOL> def __getitem__ ( self , key ) : return self . environ [ key ] <EOL> def __delitem__ ( self , key ) : self [ key ] = "<STR_LIT>" ; del ( self . environ [ key ] ) <EOL> def __iter__ ( self ) : return iter ( self . environ ) <EOL> def __len__ ( self ) : return len ( self . environ ) <EOL> def keys ( self ) : return self . environ . keys ( ) <EOL> def __setitem__ ( self , key , value ) : <EOL> """<STR_LIT>""" <EOL> if self . environ . get ( '<STR_LIT>' ) : <EOL> raise KeyError ( '<STR_LIT>' ) <EOL> self . environ [ key ] = value <EOL> todelete = ( ) <EOL> if key == '<STR_LIT>' : <EOL> todelete = ( '<STR_LIT:body>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) <EOL> elif key == '<STR_LIT>' : <EOL> todelete = ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> elif key . startswith ( '<STR_LIT>' ) : <EOL> todelete = ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> for key in todelete : <EOL> self . environ . pop ( '<STR_LIT>' + key , None ) <EOL> def __repr__ ( self ) : <EOL> return '<STR_LIT>' % ( self . __class__ . __name__ , self . method , self . url ) <EOL> def __getattr__ ( self , name ) : <EOL> '''<STR_LIT>''' <EOL> try : <EOL> var = self . environ [ '<STR_LIT>' % name ] <EOL> return var . __get__ ( self ) if hasattr ( var , '<STR_LIT>' ) else var <EOL> except KeyError : <EOL> raise AttributeError ( '<STR_LIT>' % name ) <EOL> def __setattr__ ( self , name , value ) : <EOL> if name == '<STR_LIT>' : return object . __setattr__ ( self , name , value ) <EOL> self . environ [ '<STR_LIT>' % name ] = value <EOL> def _hkey ( s ) : <EOL> return s . title ( ) . replace ( '<STR_LIT:_>' , '<STR_LIT:->' ) <EOL> class HeaderProperty ( object ) : <EOL> def __init__ ( self , name , reader = None , writer = str , default = '<STR_LIT>' ) : <EOL> self . name , self . default = name , default <EOL> self . reader , self . writer = reader , writer <EOL> self . __doc__ = '<STR_LIT>' % name . title ( ) <EOL> def __get__ ( self , obj , cls ) : <EOL> if obj is None : return self <EOL> value = obj . headers . get ( self . name , self . default ) <EOL> return self . reader ( value ) if self . reader else value <EOL> def __set__ ( self , obj , value ) : <EOL> obj . headers [ self . name ] = self . writer ( value ) <EOL> def __delete__ ( self , obj ) : <EOL> del obj . headers [ self . name ] <EOL> class BaseResponse ( object ) : <EOL> """<STR_LIT>""" <EOL> default_status = <NUM_LIT:200> <EOL> default_content_type = '<STR_LIT>' <EOL> bad_headers = { <EOL> <NUM_LIT> : set ( ( '<STR_LIT:Content-Type>' , ) ) , <EOL> <NUM_LIT> : set ( ( '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT:Content-Type>' , <EOL> '<STR_LIT>' , '<STR_LIT>' ) ) } <EOL> def __init__ ( self , body = '<STR_LIT>' , status = None , headers = None , ** more_headers ) : <EOL> self . _cookies = None <EOL> self . _headers = { } <EOL> self . body = body <EOL> self . status = status or self . default_status <EOL> if headers : <EOL> if isinstance ( headers , dict ) : <EOL> headers = headers . items ( ) <EOL> for name , value in headers : <EOL> self . add_header ( name , value ) <EOL> if more_headers : <EOL> for name , value in more_headers . items ( ) : <EOL> self . add_header ( name , value ) <EOL> def copy ( self ) : <EOL> '''<STR_LIT>''' <EOL> copy = Response ( ) <EOL> copy . status = self . status <EOL> copy . _headers = dict ( ( k , v [ : ] ) for ( k , v ) in self . _headers . items ( ) ) <EOL> return copy <EOL> def __iter__ ( self ) : <EOL> return iter ( self . body ) <EOL> def close ( self ) : <EOL> if hasattr ( self . body , '<STR_LIT>' ) : <EOL> self . body . close ( ) <EOL> @ property <EOL> def status_line ( self ) : <EOL> '''<STR_LIT>''' <EOL> return self . _status_line <EOL> @ property <EOL> def status_code ( self ) : <EOL> '''<STR_LIT>''' <EOL> return self . _status_code <EOL> def _set_status ( self , status ) : <EOL> if isinstance ( status , int ) : <EOL> code , status = status , _HTTP_STATUS_LINES . get ( status ) <EOL> elif '<STR_LIT:U+0020>' in status : <EOL> status = status . strip ( ) <EOL> code = int ( status . split ( ) [ <NUM_LIT:0> ] ) <EOL> else : <EOL> raise ValueError ( '<STR_LIT>' ) <EOL> if not <NUM_LIT:100> <= code <= <NUM_LIT> : raise ValueError ( '<STR_LIT>' ) <EOL> self . _status_code = code <EOL> self . _status_line = str ( status or ( '<STR_LIT>' % code ) ) <EOL> def _get_status ( self ) : <EOL> return self . _status_line <EOL> status = property ( _get_status , _set_status , None , <EOL> '''<STR_LIT>''' ) <EOL> del _get_status , _set_status <EOL> @ property <EOL> def headers ( self ) : <EOL> '''<STR_LIT>''' <EOL> hdict = HeaderDict ( ) <EOL> hdict . dict = self . _headers <EOL> return hdict <EOL> def __contains__ ( self , name ) : return _hkey ( name ) in self . _headers <EOL> def __delitem__ ( self , name ) : del self . _headers [ _hkey ( name ) ] <EOL> def __getitem__ ( self , name ) : return self . _headers [ _hkey ( name ) ] [ - <NUM_LIT:1> ] <EOL> def __setitem__ ( self , name , value ) : self . _headers [ _hkey ( name ) ] = [ str ( value ) ] <EOL> def get_header ( self , name , default = None ) : <EOL> '''<STR_LIT>''' <EOL> return self . _headers . get ( _hkey ( name ) , [ default ] ) [ - <NUM_LIT:1> ] <EOL> def set_header ( self , name , value ) : <EOL> '''<STR_LIT>''' <EOL> self . _headers [ _hkey ( name ) ] = [ str ( value ) ] <EOL> def add_header ( self , name , value ) : <EOL> '''<STR_LIT>''' <EOL> self . _headers . setdefault ( _hkey ( name ) , [ ] ) . append ( str ( value ) ) <EOL> def iter_headers ( self ) : <EOL> '''<STR_LIT>''' <EOL> return self . headerlist <EOL> def wsgiheader ( self ) : <EOL> depr ( '<STR_LIT>' ) <EOL> return self . headerlist <EOL> @ property <EOL> def headerlist ( self ) : <EOL> '''<STR_LIT>''' <EOL> out = [ ] <EOL> headers = list ( self . _headers . items ( ) ) <EOL> if '<STR_LIT:Content-Type>' not in self . _headers : <EOL> headers . append ( ( '<STR_LIT:Content-Type>' , [ self . default_content_type ] ) ) <EOL> if self . _status_code in self . bad_headers : <EOL> bad_headers = self . bad_headers [ self . _status_code ] <EOL> headers = [ h for h in headers if h [ <NUM_LIT:0> ] not in bad_headers ] <EOL> out += [ ( name , val ) for name , vals in headers for val in vals ] <EOL> if self . _cookies : <EOL> for c in self . _cookies . values ( ) : <EOL> out . append ( ( '<STR_LIT>' , c . OutputString ( ) ) ) <EOL> return out <EOL> content_type = HeaderProperty ( '<STR_LIT:Content-Type>' ) <EOL> content_length = HeaderProperty ( '<STR_LIT>' , reader = int ) <EOL> @ property <EOL> def charset ( self , default = '<STR_LIT>' ) : <EOL> """<STR_LIT>""" <EOL> if '<STR_LIT>' in self . content_type : <EOL> return self . content_type . split ( '<STR_LIT>' ) [ - <NUM_LIT:1> ] . split ( '<STR_LIT:;>' ) [ <NUM_LIT:0> ] . strip ( ) <EOL> return default <EOL> @ property <EOL> def COOKIES ( self ) : <EOL> """<STR_LIT>""" <EOL> depr ( '<STR_LIT>' ) <EOL> if not self . _cookies : <EOL> self . _cookies = SimpleCookie ( ) <EOL> return self . _cookies <EOL> def set_cookie ( self , name , value , secret = None , ** options ) : <EOL> '''<STR_LIT>''' <EOL> if not self . _cookies : <EOL> self . _cookies = SimpleCookie ( ) <EOL> if secret : <EOL> value = touni ( cookie_encode ( ( name , value ) , secret ) ) <EOL> elif not isinstance ( value , basestring ) : <EOL> raise TypeError ( '<STR_LIT>' ) <EOL> if len ( value ) > <NUM_LIT> : raise ValueError ( '<STR_LIT>' ) <EOL> self . _cookies [ name ] = value <EOL> for key , value in options . items ( ) : <EOL> if key == '<STR_LIT>' : <EOL> if isinstance ( value , timedelta ) : <EOL> value = value . seconds + value . days * <NUM_LIT> * <NUM_LIT> <EOL> if key == '<STR_LIT>' : <EOL> if isinstance ( value , ( datedate , datetime ) ) : <EOL> value = value . timetuple ( ) <EOL> elif isinstance ( value , ( int , float ) ) : <EOL> value = time . gmtime ( value ) <EOL> value = time . strftime ( "<STR_LIT>" , value ) <EOL> self . _cookies [ name ] [ key . replace ( '<STR_LIT:_>' , '<STR_LIT:->' ) ] = value <EOL> def delete_cookie ( self , key , ** kwargs ) : <EOL> '''<STR_LIT>''' <EOL> kwargs [ '<STR_LIT>' ] = - <NUM_LIT:1> <EOL> kwargs [ '<STR_LIT>' ] = <NUM_LIT:0> <EOL> self . set_cookie ( key , '<STR_LIT>' , ** kwargs ) <EOL> def __repr__ ( self ) : <EOL> out = '<STR_LIT>' <EOL> for name , value in self . headerlist : <EOL> out += '<STR_LIT>' % ( name . title ( ) , value . strip ( ) ) <EOL> return out <EOL> _lctx = threading . local ( ) <EOL> def local_property ( name ) : <EOL> def fget ( self ) : <EOL> try : <EOL> return getattr ( _lctx , name ) <EOL> except AttributeError : <EOL> raise RuntimeError ( "<STR_LIT>" ) <EOL> def fset ( self , value ) : setattr ( _lctx , name , value ) <EOL> def fdel ( self ) : delattr ( _lctx , name ) <EOL> return property ( fget , fset , fdel , <EOL> '<STR_LIT>' % name ) <EOL> class LocalRequest ( BaseRequest ) : <EOL> '''<STR_LIT>''' <EOL> bind = BaseRequest . __init__ <EOL> environ = local_property ( '<STR_LIT>' ) <EOL> class LocalResponse ( BaseResponse ) : <EOL> '''<STR_LIT>''' <EOL> bind = BaseResponse . __init__ <EOL> _status_line = local_property ( '<STR_LIT>' ) <EOL> _status_code = local_property ( '<STR_LIT>' ) <EOL> _cookies = local_property ( '<STR_LIT>' ) <EOL> _headers = local_property ( '<STR_LIT>' ) <EOL> body = local_property ( '<STR_LIT>' ) <EOL> Request = BaseRequest <EOL> Response = BaseResponse <EOL> class HTTPResponse ( Response , BottleException ) : <EOL> def __init__ ( self , body = '<STR_LIT>' , status = None , headers = None , <EOL> header = None , ** more_headers ) : <EOL> if header or '<STR_LIT>' in more_headers : <EOL> depr ( '<STR_LIT>' ) <EOL> if header : more_headers . update ( header ) <EOL> if '<STR_LIT>' in more_headers : body = more_headers . pop ( '<STR_LIT>' ) <EOL> super ( HTTPResponse , self ) . __init__ ( body , status , headers , ** more_headers ) <EOL> def apply ( self , response ) : <EOL> response . _status_code = self . _status_code <EOL> response . _status_line = self . _status_line <EOL> response . _headers = self . _headers <EOL> response . _cookies = self . _cookies <EOL> response . body = self . body <EOL> def _output ( self , value = None ) : <EOL> depr ( '<STR_LIT>' ) <EOL> if value is None : return self . body <EOL> self . body = value <EOL> output = property ( _output , _output , doc = '<STR_LIT>' ) <EOL> class HTTPError ( HTTPResponse ) : <EOL> default_status = <NUM_LIT> <EOL> def __init__ ( self , status = None , body = None , exception = None , traceback = None , <EOL> ** options ) : <EOL> self . exception = exception <EOL> self . traceback = traceback <EOL> super ( HTTPError , self ) . __init__ ( body , status , ** options ) <EOL> class PluginError ( BottleException ) : pass <EOL> class JSONPlugin ( object ) : <EOL> name = '<STR_LIT>' <EOL> api = <NUM_LIT:2> <EOL> def __init__ ( self , json_dumps = json_dumps ) : <EOL> self . json_dumps = json_dumps <EOL> def apply ( self , callback , route ) : <EOL> dumps = self . json_dumps <EOL> if not dumps : return callback <EOL> def wrapper ( * a , ** ka ) : <EOL> try : <EOL> rv = callback ( * a , ** ka ) <EOL> except HTTPError : <EOL> rv = _e ( ) <EOL> if isinstance ( rv , dict ) : <EOL> json_response = dumps ( rv ) <EOL> response . content_type = '<STR_LIT:application/json>' <EOL> return json_response <EOL> elif isinstance ( rv , HTTPResponse ) and isinstance ( rv . body , dict ) : <EOL> rv . body = dumps ( rv . body ) <EOL> rv . content_type = '<STR_LIT:application/json>' <EOL> return rv <EOL> return wrapper <EOL> class HooksPlugin ( object ) : <EOL> name = '<STR_LIT>' <EOL> api = <NUM_LIT:2> <EOL> _names = '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' <EOL> def __init__ ( self ) : <EOL> self . hooks = dict ( ( name , [ ] ) for name in self . _names ) <EOL> self . app = None <EOL> def _empty ( self ) : <EOL> return not ( self . hooks [ '<STR_LIT>' ] or self . hooks [ '<STR_LIT>' ] ) <EOL> def setup ( self , app ) : <EOL> self . app = app <EOL> def add ( self , name , func ) : <EOL> '''<STR_LIT>''' <EOL> was_empty = self . _empty ( ) <EOL> self . hooks . setdefault ( name , [ ] ) . append ( func ) <EOL> if self . app and was_empty and not self . _empty ( ) : self . app . reset ( ) <EOL> def remove ( self , name , func ) : <EOL> '''<STR_LIT>''' <EOL> was_empty = self . _empty ( ) <EOL> if name in self . hooks and func in self . hooks [ name ] : <EOL> self . hooks [ name ] . remove ( func ) <EOL> if self . app and not was_empty and self . _empty ( ) : self . app . reset ( ) <EOL> def trigger ( self , name , * a , ** ka ) : <EOL> '''<STR_LIT>''' <EOL> hooks = self . hooks [ name ] <EOL> if ka . pop ( '<STR_LIT>' , False ) : hooks = hooks [ : : - <NUM_LIT:1> ] <EOL> return [ hook ( * a , ** ka ) for hook in hooks ] <EOL> def apply ( self , callback , route ) : <EOL> if self . _empty ( ) : return callback <EOL> def wrapper ( * a , ** ka ) : <EOL> self . trigger ( '<STR_LIT>' ) <EOL> rv = callback ( * a , ** ka ) <EOL> self . trigger ( '<STR_LIT>' , reversed = True ) <EOL> return rv <EOL> return wrapper <EOL> class TemplatePlugin ( object ) : <EOL> '''<STR_LIT>''' <EOL> name = '<STR_LIT>' <EOL> api = <NUM_LIT:2> <EOL> def apply ( self , callback , route ) : <EOL> conf = route . config . get ( '<STR_LIT>' ) <EOL> if isinstance ( conf , ( tuple , list ) ) and len ( conf ) == <NUM_LIT:2> : <EOL> return view ( conf [ <NUM_LIT:0> ] , ** conf [ <NUM_LIT:1> ] ) ( callback ) <EOL> elif isinstance ( conf , str ) : <EOL> return view ( conf ) ( callback ) <EOL> else : <EOL> return callback <EOL> class _ImportRedirect ( object ) : <EOL> def __init__ ( self , name , impmask ) : <EOL> '''<STR_LIT>''' <EOL> self . name = name <EOL> self . impmask = impmask <EOL> self . module = sys . modules . setdefault ( name , imp . new_module ( name ) ) <EOL> self . module . __dict__ . update ( { '<STR_LIT>' : __file__ , '<STR_LIT>' : [ ] , <EOL> '<STR_LIT>' : [ ] , '<STR_LIT>' : self } ) <EOL> sys . meta_path . append ( self ) <EOL> def find_module ( self , fullname , path = None ) : <EOL> if '<STR_LIT:.>' not in fullname : return <EOL> packname , modname = fullname . rsplit ( '<STR_LIT:.>' , <NUM_LIT:1> ) <EOL> if packname != self . name : return <EOL> return self <EOL> def load_module ( self , fullname ) : <EOL> if fullname in sys . modules : return sys . modules [ fullname ] <EOL> packname , modname = fullname . rsplit ( '<STR_LIT:.>' , <NUM_LIT:1> ) <EOL> realname = self . impmask % modname <EOL> __import__ ( realname ) <EOL> module = sys . modules [ fullname ] = sys . modules [ realname ] <EOL> setattr ( self . module , modname , module ) <EOL> module . __loader__ = self <EOL> return module <EOL> class MultiDict ( DictMixin ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , * a , ** k ) : <EOL> self . dict = dict ( ( k , [ v ] ) for ( k , v ) in dict ( * a , ** k ) . items ( ) ) <EOL> def __len__ ( self ) : return len ( self . dict ) <EOL> def __iter__ ( self ) : return iter ( self . dict ) <EOL> def __contains__ ( self , key ) : return key in self . dict <EOL> def __delitem__ ( self , key ) : del self . dict [ key ] <EOL> def __getitem__ ( self , key ) : return self . dict [ key ] [ - <NUM_LIT:1> ] <EOL> def __setitem__ ( self , key , value ) : self . append ( key , value ) <EOL> def keys ( self ) : return self . dict . keys ( ) <EOL> if py3k : <EOL> def values ( self ) : return ( v [ - <NUM_LIT:1> ] for v in self . dict . values ( ) ) <EOL> def items ( self ) : return ( ( k , v [ - <NUM_LIT:1> ] ) for k , v in self . dict . items ( ) ) <EOL> def allitems ( self ) : <EOL> return ( ( k , v ) for k , vl in self . dict . items ( ) for v in vl ) <EOL> iterkeys = keys <EOL> itervalues = values <EOL> iteritems = items <EOL> iterallitems = allitems <EOL> else : <EOL> def values ( self ) : return [ v [ - <NUM_LIT:1> ] for v in self . dict . values ( ) ] <EOL> def items ( self ) : return [ ( k , v [ - <NUM_LIT:1> ] ) for k , v in self . dict . items ( ) ] <EOL> def iterkeys ( self ) : return self . dict . iterkeys ( ) <EOL> def itervalues ( self ) : return ( v [ - <NUM_LIT:1> ] for v in self . dict . itervalues ( ) ) <EOL> def iteritems ( self ) : <EOL> return ( ( k , v [ - <NUM_LIT:1> ] ) for k , v in self . dict . iteritems ( ) ) <EOL> def iterallitems ( self ) : <EOL> return ( ( k , v ) for k , vl in self . dict . iteritems ( ) for v in vl ) <EOL> def allitems ( self ) : <EOL> return [ ( k , v ) for k , vl in self . dict . iteritems ( ) for v in vl ] <EOL> def get ( self , key , default = None , index = - <NUM_LIT:1> , type = None ) : <EOL> '''<STR_LIT>''' <EOL> try : <EOL> val = self . dict [ key ] [ index ] <EOL> return type ( val ) if type else val <EOL> except Exception : <EOL> pass <EOL> return default <EOL> def append ( self , key , value ) : <EOL> '''<STR_LIT>''' <EOL> self . dict . setdefault ( key , [ ] ) . append ( value ) <EOL> def replace ( self , key , value ) : <EOL> '''<STR_LIT>''' <EOL> self . dict [ key ] = [ value ] <EOL> def getall ( self , key ) : <EOL> '''<STR_LIT>''' <EOL> return self . dict . get ( key ) or [ ] <EOL> getone = get <EOL> getlist = getall <EOL> class FormsDict ( MultiDict ) : <EOL> '''<STR_LIT>''' <EOL> input_encoding = '<STR_LIT:utf8>' <EOL> recode_unicode = True <EOL> def _fix ( self , s , encoding = None ) : <EOL> if isinstance ( s , unicode ) and self . recode_unicode : <EOL> s = s . encode ( '<STR_LIT>' ) <EOL> if isinstance ( s , bytes ) : <EOL> return s . decode ( encoding or self . input_encoding ) <EOL> return s <EOL> def decode ( self , encoding = None ) : <EOL> '''<STR_LIT>''' <EOL> copy = FormsDict ( ) <EOL> enc = copy . input_encoding = encoding or self . input_encoding <EOL> copy . recode_unicode = False <EOL> for key , value in self . allitems ( ) : <EOL> copy . append ( self . _fix ( key , enc ) , self . _fix ( value , enc ) ) <EOL> return copy <EOL> def getunicode ( self , name , default = None , encoding = None ) : <EOL> '''<STR_LIT>''' <EOL> try : <EOL> return self . _fix ( self [ name ] , encoding ) <EOL> except ( UnicodeError , KeyError ) : <EOL> return default <EOL> def __getattr__ ( self , name , default = unicode ( ) ) : <EOL> if name . startswith ( '<STR_LIT>' ) and name . endswith ( '<STR_LIT>' ) : <EOL> return super ( FormsDict , self ) . __getattr__ ( name ) <EOL> return self . getunicode ( name , default = default ) <EOL> class HeaderDict ( MultiDict ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , * a , ** ka ) : <EOL> self . dict = { } <EOL> if a or ka : self . update ( * a , ** ka ) <EOL> def __contains__ ( self , key ) : return _hkey ( key ) in self . dict <EOL> def __delitem__ ( self , key ) : del self . dict [ _hkey ( key ) ] <EOL> def __getitem__ ( self , key ) : return self . dict [ _hkey ( key ) ] [ - <NUM_LIT:1> ] <EOL> def __setitem__ ( self , key , value ) : self . dict [ _hkey ( key ) ] = [ str ( value ) ] <EOL> def append ( self , key , value ) : <EOL> self . dict . setdefault ( _hkey ( key ) , [ ] ) . append ( str ( value ) ) <EOL> def replace ( self , key , value ) : self . dict [ _hkey ( key ) ] = [ str ( value ) ] <EOL> def getall ( self , key ) : return self . dict . get ( _hkey ( key ) ) or [ ] <EOL> def get ( self , key , default = None , index = - <NUM_LIT:1> ) : <EOL> return MultiDict . get ( self , _hkey ( key ) , default , index ) <EOL> def filter ( self , names ) : <EOL> for name in [ _hkey ( n ) for n in names ] : <EOL> if name in self . dict : <EOL> del self . dict [ name ] <EOL> class WSGIHeaderDict ( DictMixin ) : <EOL> '''<STR_LIT>''' <EOL> cgikeys = ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> def __init__ ( self , environ ) : <EOL> self . environ = environ <EOL> def _ekey ( self , key ) : <EOL> '''<STR_LIT>''' <EOL> key = key . replace ( '<STR_LIT:->' , '<STR_LIT:_>' ) . upper ( ) <EOL> if key in self . cgikeys : <EOL> return key <EOL> return '<STR_LIT>' + key <EOL> def raw ( self , key , default = None ) : <EOL> '''<STR_LIT>''' <EOL> return self . environ . get ( self . _ekey ( key ) , default ) <EOL> def __getitem__ ( self , key ) : <EOL> return tonat ( self . environ [ self . _ekey ( key ) ] , '<STR_LIT>' ) <EOL> def __setitem__ ( self , key , value ) : <EOL> raise TypeError ( "<STR_LIT>" % self . __class__ ) <EOL> def __delitem__ ( self , key ) : <EOL> raise TypeError ( "<STR_LIT>" % self . __class__ ) <EOL> def __iter__ ( self ) : <EOL> for key in self . environ : <EOL> if key [ : <NUM_LIT:5> ] == '<STR_LIT>' : <EOL> yield key [ <NUM_LIT:5> : ] . replace ( '<STR_LIT:_>' , '<STR_LIT:->' ) . title ( ) <EOL> elif key in self . cgikeys : <EOL> yield key . replace ( '<STR_LIT:_>' , '<STR_LIT:->' ) . title ( ) <EOL> def keys ( self ) : return [ x for x in self ] <EOL> def __len__ ( self ) : return len ( self . keys ( ) ) <EOL> def __contains__ ( self , key ) : return self . _ekey ( key ) in self . environ <EOL> class ConfigDict ( dict ) : <EOL> '''<STR_LIT>''' <EOL> def __getattr__ ( self , key ) : <EOL> if key not in self and key [ <NUM_LIT:0> ] . isupper ( ) : <EOL> self [ key ] = ConfigDict ( ) <EOL> return self . get ( key ) <EOL> def __setattr__ ( self , key , value ) : <EOL> if hasattr ( dict , key ) : <EOL> raise AttributeError ( '<STR_LIT>' ) <EOL> if key in self and self [ key ] and isinstance ( self [ key ] , ConfigDict ) : <EOL> raise AttributeError ( '<STR_LIT>' ) <EOL> self [ key ] = value <EOL> def __delattr__ ( self , key ) : <EOL> if key in self : del self [ key ] <EOL> def __call__ ( self , * a , ** ka ) : <EOL> for key , value in dict ( * a , ** ka ) . items ( ) : setattr ( self , key , value ) <EOL> return self <EOL> class AppStack ( list ) : <EOL> """<STR_LIT>""" <EOL> def __call__ ( self ) : <EOL> """<STR_LIT>""" <EOL> return self [ - <NUM_LIT:1> ] <EOL> def push ( self , value = None ) : <EOL> """<STR_LIT>""" <EOL> if not isinstance ( value , Bottle ) : <EOL> value = Bottle ( ) <EOL> self . append ( value ) <EOL> return value <EOL> class WSGIFileWrapper ( object ) : <EOL> def __init__ ( self , fp , buffer_size = <NUM_LIT> * <NUM_LIT:64> ) : <EOL> self . fp , self . buffer_size = fp , buffer_size <EOL> for attr in ( '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) : <EOL> if hasattr ( fp , attr ) : setattr ( self , attr , getattr ( fp , attr ) ) <EOL> def __iter__ ( self ) : <EOL> buff , read = self . buffer_size , self . read <EOL> while True : <EOL> part = read ( buff ) <EOL> if not part : return <EOL> yield part <EOL> class _closeiter ( object ) : <EOL> '''<STR_LIT>''' <EOL> def __init__ ( self , iterator , close = None ) : <EOL> self . iterator = iterator <EOL> self . close_callbacks = makelist ( close ) <EOL> def __iter__ ( self ) : <EOL> return iter ( self . iterator ) <EOL> def close ( self ) : <EOL> for func in self . close_callbacks : <EOL> func ( ) <EOL> class ResourceManager ( object ) : <EOL> '''<STR_LIT>''' <EOL> def __init__ ( self , base = '<STR_LIT>' , opener = open , cachemode = '<STR_LIT:all>' ) : <EOL> self . opener = open <EOL> self . base = base <EOL> self . cachemode = cachemode <EOL> self . path = [ ] <EOL> self . cache = { } <EOL> def add_path ( self , path , base = None , index = None , create = False ) : <EOL> '''<STR_LIT>''' <EOL> base = os . path . abspath ( os . path . dirname ( base or self . base ) ) <EOL> path = os . path . abspath ( os . path . join ( base , os . path . dirname ( path ) ) ) <EOL> path += os . sep <EOL> if path in self . path : <EOL> self . path . remove ( path ) <EOL> if create and not os . path . isdir ( path ) : <EOL> os . makedirs ( path ) <EOL> if index is None : <EOL> self . path . append ( path ) <EOL> else : <EOL> self . path . insert ( index , path ) <EOL> self . cache . clear ( ) <EOL> return os . path . exists ( path ) <EOL> def __iter__ ( self ) : <EOL> '''<STR_LIT>''' <EOL> search = self . path [ : ] <EOL> while search : <EOL> path = search . pop ( ) <EOL> if not os . path . isdir ( path ) : continue <EOL> for name in os . listdir ( path ) : <EOL> full = os . path . join ( path , name ) <EOL> if os . path . isdir ( full ) : search . append ( full ) <EOL> else : yield full <EOL> def lookup ( self , name ) : <EOL> '''<STR_LIT>''' <EOL> if name not in self . cache or DEBUG : <EOL> for path in self . path : <EOL> fpath = os . path . join ( path , name ) <EOL> if os . path . isfile ( fpath ) : <EOL> if self . cachemode in ( '<STR_LIT:all>' , '<STR_LIT>' ) : <EOL> self . cache [ name ] = fpath <EOL> return fpath <EOL> if self . cachemode == '<STR_LIT:all>' : <EOL> self . cache [ name ] = None <EOL> return self . cache [ name ] <EOL> def open ( self , name , mode = '<STR_LIT:r>' , * args , ** kwargs ) : <EOL> '''<STR_LIT>''' <EOL> fname = self . lookup ( name ) <EOL> if not fname : raise IOError ( "<STR_LIT>" % name ) <EOL> return self . opener ( name , mode = mode , * args , ** kwargs ) <EOL> class FileUpload ( object ) : <EOL> def __init__ ( self , fileobj , name , filename , headers = None ) : <EOL> '''<STR_LIT>''' <EOL> self . file = fileobj <EOL> self . name = name <EOL> self . raw_filename = filename <EOL> self . headers = HeaderDict ( headers ) if headers else HeaderDict ( ) <EOL> content_type = HeaderProperty ( '<STR_LIT:Content-Type>' ) <EOL> content_length = HeaderProperty ( '<STR_LIT>' , reader = int , default = - <NUM_LIT:1> ) <EOL> @ cached_property <EOL> def filename ( self ) : <EOL> '''<STR_LIT>''' <EOL> from unicodedata import normalize <EOL> fname = self . raw_filename <EOL> if isinstance ( fname , unicode ) : <EOL> fname = normalize ( '<STR_LIT>' , fname ) . encode ( '<STR_LIT>' , '<STR_LIT:ignore>' ) <EOL> fname = fname . decode ( '<STR_LIT>' , '<STR_LIT:ignore>' ) <EOL> fname = os . path . basename ( fname . replace ( '<STR_LIT:\\>' , os . path . sep ) ) <EOL> fname = re . sub ( r'<STR_LIT>' , '<STR_LIT>' , fname ) . strip ( ) . lower ( ) <EOL> fname = re . sub ( r'<STR_LIT>' , '<STR_LIT:->' , fname . strip ( '<STR_LIT:.>' ) . strip ( ) ) <EOL> return fname or '<STR_LIT>' <EOL> def _copy_file ( self , fp , chunk_size = <NUM_LIT:2> ** <NUM_LIT:16> ) : <EOL> read , write , offset = self . file . read , fp . write , self . file . tell ( ) <EOL> while <NUM_LIT:1> : <EOL> buf = read ( chunk_size ) <EOL> if not buf : break <EOL> write ( buf ) <EOL> self . file . seek ( offset ) <EOL> def save ( self , destination , overwrite = False , chunk_size = <NUM_LIT:2> ** <NUM_LIT:16> ) : <EOL> '''<STR_LIT>''' <EOL> if isinstance ( destination , basestring ) : <EOL> if os . path . isdir ( destination ) : <EOL> destination = os . path . join ( destination , self . filename ) <EOL> if not overwrite and os . path . exists ( destination ) : <EOL> raise IOError ( '<STR_LIT>' ) <EOL> with open ( destination , '<STR_LIT:wb>' ) as fp : <EOL> self . _copy_file ( fp , chunk_size ) <EOL> else : <EOL> self . _copy_file ( destination , chunk_size ) <EOL> def abort ( code = <NUM_LIT> , text = '<STR_LIT>' ) : <EOL> """<STR_LIT>""" <EOL> raise HTTPError ( code , text ) <EOL> def redirect ( url , code = None ) : <EOL> """<STR_LIT>""" <EOL> if code is None : <EOL> code = <NUM_LIT> if request . get ( '<STR_LIT>' ) == "<STR_LIT>" else <NUM_LIT> <EOL> location = urljoin ( request . url , url ) <EOL> raise HTTPResponse ( "<STR_LIT>" , status = code , Location = location ) <EOL> def _file_iter_range ( fp , offset , bytes , maxread = <NUM_LIT> * <NUM_LIT> ) : <EOL> '''<STR_LIT>''' <EOL> fp . seek ( offset ) <EOL> while bytes > <NUM_LIT:0> : <EOL> part = fp . read ( min ( bytes , maxread ) ) <EOL> if not part : break <EOL> bytes -= len ( part ) <EOL> yield part <EOL> def static_file ( filename , root , mimetype = '<STR_LIT>' , download = False ) : <EOL> """<STR_LIT>""" <EOL> root = os . path . abspath ( root ) + os . sep <EOL> filename = os . path . abspath ( os . path . join ( root , filename . strip ( '<STR_LIT>' ) ) ) <EOL> headers = dict ( ) <EOL> if not filename . startswith ( root ) : <EOL> return HTTPError ( <NUM_LIT> , "<STR_LIT>" ) <EOL> if not os . path . exists ( filename ) or not os . path . isfile ( filename ) : <EOL> return HTTPError ( <NUM_LIT> , "<STR_LIT>" ) <EOL> if not os . access ( filename , os . R_OK ) : <EOL> return HTTPError ( <NUM_LIT> , "<STR_LIT>" ) <EOL> if mimetype == '<STR_LIT>' : <EOL> mimetype , encoding = mimetypes . guess_type ( filename ) <EOL> if mimetype : headers [ '<STR_LIT:Content-Type>' ] = mimetype <EOL> if encoding : headers [ '<STR_LIT>' ] = encoding <EOL> elif mimetype : <EOL> headers [ '<STR_LIT:Content-Type>' ] = mimetype <EOL> if download : <EOL> download = os . path . basename ( filename if download == True else download ) <EOL> headers [ '<STR_LIT>' ] = '<STR_LIT>' % download <EOL> stats = os . stat ( filename ) <EOL> headers [ '<STR_LIT>' ] = clen = stats . st_size <EOL> lm = time . strftime ( "<STR_LIT>" , time . gmtime ( stats . st_mtime ) ) <EOL> headers [ '<STR_LIT>' ] = lm <EOL> ims = request . environ . get ( '<STR_LIT>' ) <EOL> if ims : <EOL> ims = parse_date ( ims . split ( "<STR_LIT:;>" ) [ <NUM_LIT:0> ] . strip ( ) ) <EOL> if ims is not None and ims >= int ( stats . st_mtime ) : <EOL> headers [ '<STR_LIT>' ] = time . strftime ( "<STR_LIT>" , time . gmtime ( ) ) <EOL> return HTTPResponse ( status = <NUM_LIT> , ** headers ) <EOL> body = '<STR_LIT>' if request . method == '<STR_LIT>' else open ( filename , '<STR_LIT:rb>' ) <EOL> headers [ "<STR_LIT>" ] = "<STR_LIT>" <EOL> ranges = request . environ . get ( '<STR_LIT>' ) <EOL> if '<STR_LIT>' in request . environ : <EOL> ranges = list ( parse_range_header ( request . environ [ '<STR_LIT>' ] , clen ) ) <EOL> if not ranges : <EOL> return HTTPError ( <NUM_LIT> , "<STR_LIT>" ) <EOL> offset , end = ranges [ <NUM_LIT:0> ] <EOL> headers [ "<STR_LIT>" ] = "<STR_LIT>" % ( offset , end - <NUM_LIT:1> , clen ) <EOL> headers [ "<STR_LIT>" ] = str ( end - offset ) <EOL> if body : body = _file_iter_range ( body , offset , end - offset ) <EOL> return HTTPResponse ( body , status = <NUM_LIT> , ** headers ) <EOL> return HTTPResponse ( body , ** headers ) <EOL> def debug ( mode = True ) : <EOL> """<STR_LIT>""" <EOL> global DEBUG <EOL> if mode : warnings . simplefilter ( '<STR_LIT:default>' ) <EOL> DEBUG = bool ( mode ) <EOL> def parse_date ( ims ) : <EOL> """<STR_LIT>""" <EOL> try : <EOL> ts = email . utils . parsedate_tz ( ims ) <EOL> return time . mktime ( ts [ : <NUM_LIT:8> ] + ( <NUM_LIT:0> , ) ) - ( ts [ <NUM_LIT:9> ] or <NUM_LIT:0> ) - time . timezone <EOL> except ( TypeError , ValueError , IndexError , OverflowError ) : <EOL> return None <EOL> def parse_auth ( header ) : <EOL> """<STR_LIT>""" <EOL> try : <EOL> method , data = header . split ( None , <NUM_LIT:1> ) <EOL> if method . lower ( ) == '<STR_LIT>' : <EOL> user , pwd = touni ( base64 . b64decode ( tob ( data ) ) ) . split ( '<STR_LIT::>' , <NUM_LIT:1> ) <EOL> return user , pwd <EOL> except ( KeyError , ValueError ) : <EOL> return None <EOL> def parse_range_header ( header , maxlen = <NUM_LIT:0> ) : <EOL> '''<STR_LIT>''' <EOL> if not header or header [ : <NUM_LIT:6> ] != '<STR_LIT>' : return <EOL> ranges = [ r . split ( '<STR_LIT:->' , <NUM_LIT:1> ) for r in header [ <NUM_LIT:6> : ] . split ( '<STR_LIT:U+002C>' ) if '<STR_LIT:->' in r ] <EOL> for start , end in ranges : <EOL> try : <EOL> if not start : <EOL> start , end = max ( <NUM_LIT:0> , maxlen - int ( end ) ) , maxlen <EOL> elif not end : <EOL> start , end = int ( start ) , maxlen <EOL> else : <EOL> start , end = int ( start ) , min ( int ( end ) + <NUM_LIT:1> , maxlen ) <EOL> if <NUM_LIT:0> <= start < end <= maxlen : <EOL> yield start , end <EOL> except ValueError : <EOL> pass <EOL> def _parse_qsl ( qs ) : <EOL> r = [ ] <EOL> for pair in qs . replace ( '<STR_LIT:;>' , '<STR_LIT:&>' ) . split ( '<STR_LIT:&>' ) : <EOL> if not pair : continue <EOL> nv = pair . split ( '<STR_LIT:=>' , <NUM_LIT:1> ) <EOL> if len ( nv ) != <NUM_LIT:2> : nv . append ( '<STR_LIT>' ) <EOL> key = urlunquote ( nv [ <NUM_LIT:0> ] . replace ( '<STR_LIT:+>' , '<STR_LIT:U+0020>' ) ) <EOL> value = urlunquote ( nv [ <NUM_LIT:1> ] . replace ( '<STR_LIT:+>' , '<STR_LIT:U+0020>' ) ) <EOL> r . append ( ( key , value ) ) <EOL> return r <EOL> def _lscmp ( a , b ) : <EOL> '''<STR_LIT>''' <EOL> return not sum ( <NUM_LIT:0> if x == y else <NUM_LIT:1> for x , y in zip ( a , b ) ) and len ( a ) == len ( b ) <EOL> def cookie_encode ( data , key ) : <EOL> '''<STR_LIT>''' <EOL> msg = base64 . b64encode ( pickle . dumps ( data , - <NUM_LIT:1> ) ) <EOL> sig = base64 . b64encode ( hmac . new ( tob ( key ) , msg ) . digest ( ) ) <EOL> return tob ( '<STR_LIT:!>' ) + sig + tob ( '<STR_LIT:?>' ) + msg <EOL> def cookie_decode ( data , key ) : <EOL> '''<STR_LIT>''' <EOL> data = tob ( data ) <EOL> if cookie_is_encoded ( data ) : <EOL> sig , msg = data . split ( tob ( '<STR_LIT:?>' ) , <NUM_LIT:1> ) <EOL> if _lscmp ( sig [ <NUM_LIT:1> : ] , base64 . b64encode ( hmac . new ( tob ( key ) , msg ) . digest ( ) ) ) : <EOL> return pickle . loads ( base64 . b64decode ( msg ) ) <EOL> return None <EOL> def cookie_is_encoded ( data ) : <EOL> '''<STR_LIT>''' <EOL> return bool ( data . startswith ( tob ( '<STR_LIT:!>' ) ) and tob ( '<STR_LIT:?>' ) in data ) <EOL> def html_escape ( string ) : <EOL> '''<STR_LIT>''' <EOL> return string . replace ( '<STR_LIT:&>' , '<STR_LIT>' ) . replace ( '<STR_LIT:<>' , '<STR_LIT>' ) . replace ( '<STR_LIT:>>' , '<STR_LIT>' ) . replace ( '<STR_LIT:">' , '<STR_LIT>' ) . replace ( "<STR_LIT:'>" , '<STR_LIT>' ) <EOL> def html_quote ( string ) : <EOL> '''<STR_LIT>''' <EOL> return '<STR_LIT>' % html_escape ( string ) . replace ( '<STR_LIT:\n>' , '<STR_LIT>' ) . replace ( '<STR_LIT:\r>' , '<STR_LIT>' ) . replace ( '<STR_LIT:\t>' , '<STR_LIT>' ) <EOL> def yieldroutes ( func ) : <EOL> """<STR_LIT>""" <EOL> import inspect <EOL> path = '<STR_LIT:/>' + func . __name__ . replace ( '<STR_LIT>' , '<STR_LIT:/>' ) . lstrip ( '<STR_LIT:/>' ) <EOL> spec = inspect . getargspec ( func ) <EOL> argc = len ( spec [ <NUM_LIT:0> ] ) - len ( spec [ <NUM_LIT:3> ] or [ ] ) <EOL> path += ( '<STR_LIT>' * argc ) % tuple ( spec [ <NUM_LIT:0> ] [ : argc ] ) <EOL> yield path <EOL> for arg in spec [ <NUM_LIT:0> ] [ argc : ] : <EOL> path += '<STR_LIT>' % arg <EOL> yield path <EOL> def path_shift ( script_name , path_info , shift = <NUM_LIT:1> ) : <EOL> '''<STR_LIT>''' <EOL> if shift == <NUM_LIT:0> : return script_name , path_info <EOL> pathlist = path_info . strip ( '<STR_LIT:/>' ) . split ( '<STR_LIT:/>' ) <EOL> scriptlist = script_name . strip ( '<STR_LIT:/>' ) . split ( '<STR_LIT:/>' ) <EOL> if pathlist and pathlist [ <NUM_LIT:0> ] == '<STR_LIT>' : pathlist = [ ] <EOL> if scriptlist and scriptlist [ <NUM_LIT:0> ] == '<STR_LIT>' : scriptlist = [ ] <EOL> if shift > <NUM_LIT:0> and shift <= len ( pathlist ) : <EOL> moved = pathlist [ : shift ] <EOL> scriptlist = scriptlist + moved <EOL> pathlist = pathlist [ shift : ] <EOL> elif shift < <NUM_LIT:0> and shift >= - len ( scriptlist ) : <EOL> moved = scriptlist [ shift : ] <EOL> pathlist = moved + pathlist <EOL> scriptlist = scriptlist [ : shift ] <EOL> else : <EOL> empty = '<STR_LIT>' if shift < <NUM_LIT:0> else '<STR_LIT>' <EOL> raise AssertionError ( "<STR_LIT>" % empty ) <EOL> new_script_name = '<STR_LIT:/>' + '<STR_LIT:/>' . join ( scriptlist ) <EOL> new_path_info = '<STR_LIT:/>' + '<STR_LIT:/>' . join ( pathlist ) <EOL> if path_info . endswith ( '<STR_LIT:/>' ) and pathlist : new_path_info += '<STR_LIT:/>' <EOL> return new_script_name , new_path_info <EOL> def auth_basic ( check , realm = "<STR_LIT>" , text = "<STR_LIT>" ) : <EOL> '''<STR_LIT>''' <EOL> def decorator ( func ) : <EOL> def wrapper ( * a , ** ka ) : <EOL> user , password = request . auth or ( None , None ) <EOL> if user is None or not check ( user , password ) : <EOL> err = HTTPError ( <NUM_LIT> , text ) <EOL> err . add_header ( '<STR_LIT>' , '<STR_LIT>' % realm ) <EOL> return err <EOL> return func ( * a , ** ka ) <EOL> return wrapper <EOL> return decorator <EOL> def make_default_app_wrapper ( name ) : <EOL> '''<STR_LIT>''' <EOL> @ functools . wraps ( getattr ( Bottle , name ) ) <EOL> def wrapper ( * a , ** ka ) : <EOL> return getattr ( app ( ) , name ) ( * a , ** ka ) <EOL> return wrapper <EOL> route = make_default_app_wrapper ( '<STR_LIT>' ) <EOL> get = make_default_app_wrapper ( '<STR_LIT>' ) <EOL> post = make_default_app_wrapper ( '<STR_LIT>' ) <EOL> put = make_default_app_wrapper ( '<STR_LIT>' ) <EOL> delete = make_default_app_wrapper ( '<STR_LIT>' ) <EOL> error = make_default_app_wrapper ( '<STR_LIT:error>' ) <EOL> mount = make_default_app_wrapper ( '<STR_LIT>' ) <EOL> hook = make_default_app_wrapper ( '<STR_LIT>' ) <EOL> install = make_default_app_wrapper ( '<STR_LIT>' ) <EOL> uninstall = make_default_app_wrapper ( '<STR_LIT>' ) <EOL> url = make_default_app_wrapper ( '<STR_LIT>' ) <EOL> class ServerAdapter ( object ) : <EOL> quiet = False <EOL> def __init__ ( self , host = '<STR_LIT:127.0.0.1>' , port = <NUM_LIT> , ** options ) : <EOL> self . options = options <EOL> self . host = host <EOL> self . port = int ( port ) <EOL> def run ( self , handler ) : <EOL> pass <EOL> def __repr__ ( self ) : <EOL> args = '<STR_LIT:U+002CU+0020>' . join ( [ '<STR_LIT>' % ( k , repr ( v ) ) for k , v in self . options . items ( ) ] ) <EOL> return "<STR_LIT>" % ( self . __class__ . __name__ , args ) <EOL> class CGIServer ( ServerAdapter ) : <EOL> quiet = True <EOL> def run ( self , handler ) : <EOL> from wsgiref . handlers import CGIHandler <EOL> def fixed_environ ( environ , start_response ) : <EOL> environ . setdefault ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> return handler ( environ , start_response ) <EOL> CGIHandler ( ) . run ( fixed_environ ) <EOL> class FlupFCGIServer ( ServerAdapter ) : <EOL> def run ( self , handler ) : <EOL> import flup . server . fcgi <EOL> self . options . setdefault ( '<STR_LIT>' , ( self . host , self . port ) ) <EOL> flup . server . fcgi . WSGIServer ( handler , ** self . options ) . run ( ) <EOL> class WSGIRefServer ( ServerAdapter ) : <EOL> def run ( self , handler ) : <EOL> from wsgiref . simple_server import make_server , WSGIRequestHandler <EOL> if self . quiet : <EOL> class QuietHandler ( WSGIRequestHandler ) : <EOL> def log_request ( * args , ** kw ) : pass <EOL> self . options [ '<STR_LIT>' ] = QuietHandler <EOL> srv = make_server ( self . host , self . port , handler , ** self . options ) <EOL> srv . serve_forever ( ) <EOL> class CherryPyServer ( ServerAdapter ) : <EOL> def run ( self , handler ) : <EOL> from cherrypy import wsgiserver <EOL> server = wsgiserver . CherryPyWSGIServer ( ( self . host , self . port ) , handler ) <EOL> try : <EOL> server . start ( ) <EOL> finally : <EOL> server . stop ( ) <EOL> class WaitressServer ( ServerAdapter ) : <EOL> def run ( self , handler ) : <EOL> from waitress import serve <EOL> serve ( handler , host = self . host , port = self . port ) <EOL> class PasteServer ( ServerAdapter ) : <EOL> def run ( self , handler ) : <EOL> from paste import httpserver <EOL> from paste . translogger import TransLogger <EOL> handler = TransLogger ( handler , setup_console_handler = ( not self . quiet ) ) <EOL> httpserver . serve ( handler , host = self . host , port = str ( self . port ) , <EOL> ** self . options ) <EOL> class MeinheldServer ( ServerAdapter ) : <EOL> def run ( self , handler ) : <EOL> from meinheld import server <EOL> server . listen ( ( self . host , self . port ) ) <EOL> server . run ( handler ) <EOL> class FapwsServer ( ServerAdapter ) : <EOL> """<STR_LIT>""" <EOL> def run ( self , handler ) : <EOL> import fapws . _evwsgi as evwsgi <EOL> from fapws import base , config <EOL> port = self . port <EOL> if float ( config . SERVER_IDENT [ - <NUM_LIT:2> : ] ) > <NUM_LIT> : <EOL> port = str ( port ) <EOL> evwsgi . start ( self . host , port ) <EOL> if '<STR_LIT>' in os . environ and not self . quiet : <EOL> _stderr ( "<STR_LIT>" ) <EOL> _stderr ( "<STR_LIT>" ) <EOL> evwsgi . set_base_module ( base ) <EOL> def app ( environ , start_response ) : <EOL> environ [ '<STR_LIT>' ] = False <EOL> return handler ( environ , start_response ) <EOL> evwsgi . wsgi_cb ( ( '<STR_LIT>' , app ) ) <EOL> evwsgi . run ( ) <EOL> class TornadoServer ( ServerAdapter ) : <EOL> """<STR_LIT>""" <EOL> def run ( self , handler ) : <EOL> import tornado . wsgi , tornado . httpserver , tornado . ioloop <EOL> container = tornado . wsgi . WSGIContainer ( handler ) <EOL> server = tornado . httpserver . HTTPServer ( container ) <EOL> server . listen ( port = self . port , address = self . host ) <EOL> tornado . ioloop . IOLoop . instance ( ) . start ( ) <EOL> class AppEngineServer ( ServerAdapter ) : <EOL> """<STR_LIT>""" <EOL> quiet = True <EOL> def run ( self , handler ) : <EOL> from google . appengine . ext . webapp import util <EOL> module = sys . modules . get ( '<STR_LIT:__main__>' ) <EOL> if module and not hasattr ( module , '<STR_LIT>' ) : <EOL> module . main = lambda : util . run_wsgi_app ( handler ) <EOL> util . run_wsgi_app ( handler ) <EOL> class TwistedServer ( ServerAdapter ) : <EOL> """<STR_LIT>""" <EOL> def run ( self , handler ) : <EOL> from twisted . web import server , wsgi <EOL> from twisted . python . threadpool import ThreadPool <EOL> from twisted . internet import reactor <EOL> thread_pool = ThreadPool ( ) <EOL> thread_pool . start ( ) <EOL> reactor . addSystemEventTrigger ( '<STR_LIT>' , '<STR_LIT>' , thread_pool . stop ) <EOL> factory = server . Site ( wsgi . WSGIResource ( reactor , thread_pool , handler ) ) <EOL> reactor . listenTCP ( self . port , factory , interface = self . host ) <EOL> reactor . run ( ) <EOL> class DieselServer ( ServerAdapter ) : <EOL> """<STR_LIT>""" <EOL> def run ( self , handler ) : <EOL> from diesel . protocols . wsgi import WSGIApplication <EOL> app = WSGIApplication ( handler , port = self . port ) <EOL> app . run ( ) <EOL> class GeventServer ( ServerAdapter ) : <EOL> """<STR_LIT>""" <EOL> def run ( self , handler ) : <EOL> from gevent import wsgi , pywsgi , local <EOL> if not isinstance ( _lctx , local . local ) : <EOL> msg = "<STR_LIT>" <EOL> raise RuntimeError ( msg ) <EOL> if not self . options . pop ( '<STR_LIT>' , None ) : wsgi = pywsgi <EOL> self . options [ '<STR_LIT>' ] = None if self . quiet else '<STR_LIT:default>' <EOL> address = ( self . host , self . port ) <EOL> wsgi . WSGIServer ( address , handler , ** self . options ) . serve_forever ( ) <EOL> class GunicornServer ( ServerAdapter ) : <EOL> """<STR_LIT>""" <EOL> def run ( self , handler ) : <EOL> from gunicorn . app . base import Application <EOL> config = { '<STR_LIT>' : "<STR_LIT>" % ( self . host , int ( self . port ) ) } <EOL> config . update ( self . options ) <EOL> class GunicornApplication ( Application ) : <EOL> def init ( self , parser , opts , args ) : <EOL> return config <EOL> def load ( self ) : <EOL> return handler <EOL> GunicornApplication ( ) . run ( ) <EOL> class EventletServer ( ServerAdapter ) : <EOL> """<STR_LIT>""" <EOL> def run ( self , handler ) : <EOL> from eventlet import wsgi , listen <EOL> try : <EOL> wsgi . server ( listen ( ( self . host , self . port ) ) , handler , <EOL> log_output = ( not self . quiet ) ) <EOL> except TypeError : <EOL> wsgi . server ( listen ( ( self . host , self . port ) ) , handler ) <EOL> class RocketServer ( ServerAdapter ) : <EOL> """<STR_LIT>""" <EOL> def run ( self , handler ) : <EOL> from rocket import Rocket <EOL> server = Rocket ( ( self . host , self . port ) , '<STR_LIT>' , { '<STR_LIT>' : handler } ) <EOL> server . start ( ) <EOL> class BjoernServer ( ServerAdapter ) : <EOL> """<STR_LIT>""" <EOL> def run ( self , handler ) : <EOL> from bjoern import run <EOL> run ( handler , self . host , self . port ) <EOL> class AutoServer ( ServerAdapter ) : <EOL> """<STR_LIT>""" <EOL> adapters = [ WaitressServer , PasteServer , TwistedServer , CherryPyServer , WSGIRefServer ] <EOL> def run ( self , handler ) : <EOL> for sa in self . adapters : <EOL> try : <EOL> return sa ( self . host , self . port , ** self . options ) . run ( handler ) <EOL> except ImportError : <EOL> pass <EOL> server_names = { <EOL> '<STR_LIT>' : CGIServer , <EOL> '<STR_LIT>' : FlupFCGIServer , <EOL> '<STR_LIT>' : WSGIRefServer , <EOL> '<STR_LIT>' : WaitressServer , <EOL> '<STR_LIT>' : CherryPyServer , <EOL> '<STR_LIT>' : PasteServer , <EOL> '<STR_LIT>' : FapwsServer , <EOL> '<STR_LIT>' : TornadoServer , <EOL> '<STR_LIT>' : AppEngineServer , <EOL> '<STR_LIT>' : TwistedServer , <EOL> '<STR_LIT>' : DieselServer , <EOL> '<STR_LIT>' : MeinheldServer , <EOL> '<STR_LIT>' : GunicornServer , <EOL> '<STR_LIT>' : EventletServer , <EOL> '<STR_LIT>' : GeventServer , <EOL> '<STR_LIT>' : RocketServer , <EOL> '<STR_LIT>' : BjoernServer , <EOL> '<STR_LIT>' : AutoServer , <EOL> } <EOL> def load ( target , ** namespace ) : <EOL> """<STR_LIT>""" <EOL> module , target = target . split ( "<STR_LIT::>" , <NUM_LIT:1> ) if '<STR_LIT::>' in target else ( target , None ) <EOL> if module not in sys . modules : __import__ ( module ) <EOL> if not target : return sys . modules [ module ] <EOL> if target . isalnum ( ) : return getattr ( sys . modules [ module ] , target ) <EOL> package_name = module . split ( '<STR_LIT:.>' ) [ <NUM_LIT:0> ] <EOL> namespace [ package_name ] = sys . modules [ package_name ] <EOL> return eval ( '<STR_LIT>' % ( module , target ) , namespace ) <EOL> def load_app ( target ) : <EOL> """<STR_LIT>""" <EOL> global NORUN ; NORUN , nr_old = True , NORUN <EOL> try : <EOL> tmp = default_app . push ( ) <EOL> rv = load ( target ) <EOL> return rv if callable ( rv ) else tmp <EOL> finally : <EOL> default_app . remove ( tmp ) <EOL> NORUN = nr_old <EOL> _debug = debug <EOL> def run ( app = None , server = '<STR_LIT>' , host = '<STR_LIT:127.0.0.1>' , port = <NUM_LIT> , <EOL> interval = <NUM_LIT:1> , reloader = False , quiet = False , plugins = None , <EOL> debug = False , ** kargs ) : <EOL> """<STR_LIT>""" <EOL> if NORUN : return <EOL> if reloader and not os . environ . get ( '<STR_LIT>' ) : <EOL> try : <EOL> lockfile = None <EOL> fd , lockfile = tempfile . mkstemp ( prefix = '<STR_LIT>' , suffix = '<STR_LIT>' ) <EOL> os . close ( fd ) <EOL> while os . path . exists ( lockfile ) : <EOL> args = [ sys . executable ] + sys . argv <EOL> environ = os . environ . copy ( ) <EOL> environ [ '<STR_LIT>' ] = '<STR_LIT:true>' <EOL> environ [ '<STR_LIT>' ] = lockfile <EOL> p = subprocess . Popen ( args , env = environ ) <EOL> while p . poll ( ) is None : <EOL> os . utime ( lockfile , None ) <EOL> time . sleep ( interval ) <EOL> if p . poll ( ) != <NUM_LIT:3> : <EOL> if os . path . exists ( lockfile ) : os . unlink ( lockfile ) <EOL> sys . exit ( p . poll ( ) ) <EOL> except KeyboardInterrupt : <EOL> pass <EOL> finally : <EOL> if os . path . exists ( lockfile ) : <EOL> os . unlink ( lockfile ) <EOL> return <EOL> try : <EOL> _debug ( debug ) <EOL> app = app or default_app ( ) <EOL> if isinstance ( app , basestring ) : <EOL> app = load_app ( app ) <EOL> if not callable ( app ) : <EOL> raise ValueError ( "<STR_LIT>" % app ) <EOL> for plugin in plugins or [ ] : <EOL> app . install ( plugin ) <EOL> if server in server_names : <EOL> server = server_names . get ( server ) <EOL> if isinstance ( server , basestring ) : <EOL> server = load ( server ) <EOL> if isinstance ( server , type ) : <EOL> server = server ( host = host , port = port , ** kargs ) <EOL> if not isinstance ( server , ServerAdapter ) : <EOL> raise ValueError ( "<STR_LIT>" % server ) <EOL> server . quiet = server . quiet or quiet <EOL> if not server . quiet : <EOL> _stderr ( "<STR_LIT>" % ( __version__ , repr ( server ) ) ) <EOL> _stderr ( "<STR_LIT>" % ( server . host , server . port ) ) <EOL> _stderr ( "<STR_LIT>" ) <EOL> if reloader : <EOL> lockfile = os . environ . get ( '<STR_LIT>' ) <EOL> bgcheck = FileCheckerThread ( lockfile , interval ) <EOL> with bgcheck : <EOL> server . run ( app ) <EOL> if bgcheck . status == '<STR_LIT>' : <EOL> sys . exit ( <NUM_LIT:3> ) <EOL> else : <EOL> server . run ( app ) <EOL> except KeyboardInterrupt : <EOL> pass <EOL> except ( SystemExit , MemoryError ) : <EOL> raise <EOL> except : <EOL> if not reloader : raise <EOL> if not getattr ( server , '<STR_LIT>' , quiet ) : <EOL> print_exc ( ) <EOL> time . sleep ( interval ) <EOL> sys . exit ( <NUM_LIT:3> ) <EOL> class FileCheckerThread ( threading . Thread ) : <EOL> '''<STR_LIT>''' <EOL> def __init__ ( self , lockfile , interval ) : <EOL> threading . Thread . __init__ ( self ) <EOL> self . lockfile , self . interval = lockfile , interval <EOL> self . status = None <EOL> def run ( self ) : <EOL> exists = os . path . exists <EOL> mtime = lambda path : os . stat ( path ) . st_mtime <EOL> files = dict ( ) <EOL> for module in list ( sys . modules . values ( ) ) : <EOL> path = getattr ( module , '<STR_LIT>' , '<STR_LIT>' ) <EOL> if path [ - <NUM_LIT:4> : ] in ( '<STR_LIT>' , '<STR_LIT>' ) : path = path [ : - <NUM_LIT:1> ] <EOL> if path and exists ( path ) : files [ path ] = mtime ( path ) <EOL> while not self . status : <EOL> if not exists ( self . lockfile ) or mtime ( self . lockfile ) < time . time ( ) - self . interval - <NUM_LIT:5> : <EOL> self . status = '<STR_LIT:error>' <EOL> thread . interrupt_main ( ) <EOL> for path , lmtime in list ( files . items ( ) ) : <EOL> if not exists ( path ) or mtime ( path ) > lmtime : <EOL> self . status = '<STR_LIT>' <EOL> thread . interrupt_main ( ) <EOL> break <EOL> time . sleep ( self . interval ) <EOL> def __enter__ ( self ) : <EOL> self . start ( ) <EOL> def __exit__ ( self , exc_type , exc_val , exc_tb ) : <EOL> if not self . status : self . status = '<STR_LIT>' <EOL> self . join ( ) <EOL> return exc_type is not None and issubclass ( exc_type , KeyboardInterrupt ) <EOL> class TemplateError ( HTTPError ) : <EOL> def __init__ ( self , message ) : <EOL> HTTPError . __init__ ( self , <NUM_LIT> , message ) <EOL> class BaseTemplate ( object ) : <EOL> """<STR_LIT>""" <EOL> extensions = [ '<STR_LIT>' , '<STR_LIT:html>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> settings = { } <EOL> defaults = { } <EOL> def __init__ ( self , source = None , name = None , lookup = [ ] , encoding = '<STR_LIT:utf8>' , ** settings ) : <EOL> """<STR_LIT>""" <EOL> self . name = name <EOL> self . source = source . read ( ) if hasattr ( source , '<STR_LIT>' ) else source <EOL> self . filename = source . filename if hasattr ( source , '<STR_LIT:filename>' ) else None <EOL> self . lookup = [ os . path . abspath ( x ) for x in lookup ] <EOL> self . encoding = encoding <EOL> self . settings = self . settings . copy ( ) <EOL> self . settings . update ( settings ) <EOL> if not self . source and self . name : <EOL> self . filename = self . search ( self . name , self . lookup ) <EOL> if not self . filename : <EOL> raise TemplateError ( '<STR_LIT>' % repr ( name ) ) <EOL> if not self . source and not self . filename : <EOL> raise TemplateError ( '<STR_LIT>' ) <EOL> self . prepare ( ** self . settings ) <EOL> @ classmethod <EOL> def search ( cls , name , lookup = [ ] ) : <EOL> """<STR_LIT>""" <EOL> if not lookup : <EOL> depr ( '<STR_LIT>' ) <EOL> lookup = [ '<STR_LIT:.>' ] <EOL> if os . path . isabs ( name ) and os . path . isfile ( name ) : <EOL> depr ( '<STR_LIT>' ) <EOL> return os . path . abspath ( name ) <EOL> for spath in lookup : <EOL> spath = os . path . abspath ( spath ) + os . sep <EOL> fname = os . path . abspath ( os . path . join ( spath , name ) ) <EOL> if not fname . startswith ( spath ) : continue <EOL> if os . path . isfile ( fname ) : return fname <EOL> for ext in cls . extensions : <EOL> if os . path . isfile ( '<STR_LIT>' % ( fname , ext ) ) : <EOL> return '<STR_LIT>' % ( fname , ext ) <EOL> @ classmethod <EOL> def global_config ( cls , key , * args ) : <EOL> '''<STR_LIT>''' <EOL> if args : <EOL> cls . settings = cls . settings . copy ( ) <EOL> cls . settings [ key ] = args [ <NUM_LIT:0> ] <EOL> else : <EOL> return cls . settings [ key ] <EOL> def prepare ( self , ** options ) : <EOL> """<STR_LIT>""" <EOL> raise NotImplementedError <EOL> def render ( self , * args , ** kwargs ) : <EOL> """<STR_LIT>""" <EOL> raise NotImplementedError <EOL> class MakoTemplate ( BaseTemplate ) : <EOL> def prepare ( self , ** options ) : <EOL> from mako . template import Template <EOL> from mako . lookup import TemplateLookup <EOL> options . update ( { '<STR_LIT>' : self . encoding } ) <EOL> options . setdefault ( '<STR_LIT>' , bool ( DEBUG ) ) <EOL> lookup = TemplateLookup ( directories = self . lookup , ** options ) <EOL> if self . source : <EOL> self . tpl = Template ( self . source , lookup = lookup , ** options ) <EOL> else : <EOL> self . tpl = Template ( uri = self . name , filename = self . filename , lookup = lookup , ** options ) <EOL> def render ( self , * args , ** kwargs ) : <EOL> for dictarg in args : kwargs . update ( dictarg ) <EOL> _defaults = self . defaults . copy ( ) <EOL> _defaults . update ( kwargs ) <EOL> return self . tpl . render ( ** _defaults ) <EOL> class CheetahTemplate ( BaseTemplate ) : <EOL> def prepare ( self , ** options ) : <EOL> from Cheetah . Template import Template <EOL> self . context = threading . local ( ) <EOL> self . context . vars = { } <EOL> options [ '<STR_LIT>' ] = [ self . context . vars ] <EOL> if self . source : <EOL> self . tpl = Template ( source = self . source , ** options ) <EOL> else : <EOL> self . tpl = Template ( file = self . filename , ** options ) <EOL> def render ( self , * args , ** kwargs ) : <EOL> for dictarg in args : kwargs . update ( dictarg ) <EOL> self . context . vars . update ( self . defaults ) <EOL> self . context . vars . update ( kwargs ) <EOL> out = str ( self . tpl ) <EOL> self . context . vars . clear ( ) <EOL> return out <EOL> class Jinja2Template ( BaseTemplate ) : <EOL> def prepare ( self , filters = None , tests = None , ** kwargs ) : <EOL> from jinja2 import Environment , FunctionLoader <EOL> if '<STR_LIT>' in kwargs : <EOL> raise RuntimeError ( '<STR_LIT>' <EOL> '<STR_LIT>' ) <EOL> self . env = Environment ( loader = FunctionLoader ( self . loader ) , ** kwargs ) <EOL> if filters : self . env . filters . update ( filters ) <EOL> if tests : self . env . tests . update ( tests ) <EOL> if self . source : <EOL> self . tpl = self . env . from_string ( self . source ) <EOL> else : <EOL> self . tpl = self . env . get_template ( self . filename ) <EOL> def render ( self , * args , ** kwargs ) : <EOL> for dictarg in args : kwargs . update ( dictarg ) <EOL> _defaults = self . defaults . copy ( ) <EOL> _defaults . update ( kwargs ) <EOL> return self . tpl . render ( ** _defaults ) <EOL> def loader ( self , name ) : <EOL> fname = self . search ( name , self . lookup ) <EOL> if not fname : return <EOL> with open ( fname , "<STR_LIT:rb>" ) as f : <EOL> return f . read ( ) . decode ( self . encoding ) <EOL> class SimpleTemplate ( BaseTemplate ) : <EOL> blocks = ( '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT:class>' ) <EOL> dedent_blocks = ( '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) <EOL> @ lazy_attribute <EOL> def re_pytokens ( cls ) : <EOL> '''<STR_LIT>''' <EOL> return re . compile ( r'''<STR_LIT>''' , re . VERBOSE ) <EOL> def prepare ( self , escape_func = html_escape , noescape = False , ** kwargs ) : <EOL> self . cache = { } <EOL> enc = self . encoding <EOL> self . _str = lambda x : touni ( x , enc ) <EOL> self . _escape = lambda x : escape_func ( touni ( x , enc ) ) <EOL> if noescape : <EOL> self . _str , self . _escape = self . _escape , self . _str <EOL> @ classmethod <EOL> def split_comment ( cls , code ) : <EOL> """<STR_LIT>""" <EOL> if '<STR_LIT:#>' not in code : return code <EOL> subf = lambda m : '<STR_LIT>' if m . group ( <NUM_LIT:0> ) [ <NUM_LIT:0> ] == '<STR_LIT:#>' else m . group ( <NUM_LIT:0> ) <EOL> return re . sub ( cls . re_pytokens , subf , code ) <EOL> @ cached_property <EOL> def co ( self ) : <EOL> return compile ( self . code , self . filename or '<STR_LIT>' , '<STR_LIT>' ) <EOL> @ cached_property <EOL> def code ( self ) : <EOL> stack = [ ] <EOL> lineno = <NUM_LIT:0> <EOL> ptrbuffer = [ ] <EOL> codebuffer = [ ] <EOL> multiline = dedent = oneline = False <EOL> template = self . source <EOL> if not template : <EOL> with open ( self . filename , '<STR_LIT:rb>' ) as fp : <EOL> template = fp . read ( ) <EOL> def yield_tokens ( line ) : <EOL> for i , part in enumerate ( re . split ( r'<STR_LIT>' , line ) ) : <EOL> if i % <NUM_LIT:2> : <EOL> if part . startswith ( '<STR_LIT:!>' ) : yield '<STR_LIT>' , part [ <NUM_LIT:1> : ] <EOL> else : yield '<STR_LIT>' , part <EOL> else : yield '<STR_LIT>' , part <EOL> def flush ( ) : <EOL> if not ptrbuffer : return <EOL> cline = '<STR_LIT>' <EOL> for line in ptrbuffer : <EOL> for token , value in line : <EOL> if token == '<STR_LIT>' : cline += repr ( value ) <EOL> elif token == '<STR_LIT>' : cline += '<STR_LIT>' % value <EOL> elif token == '<STR_LIT>' : cline += '<STR_LIT>' % value <EOL> cline += '<STR_LIT:U+002CU+0020>' <EOL> cline = cline [ : - <NUM_LIT:2> ] + '<STR_LIT>' <EOL> cline = cline [ : - <NUM_LIT:2> ] <EOL> if cline [ : - <NUM_LIT:1> ] . endswith ( '<STR_LIT>' ) : <EOL> cline = cline [ : - <NUM_LIT:7> ] + cline [ - <NUM_LIT:1> ] <EOL> cline = '<STR_LIT>' + cline + '<STR_LIT>' <EOL> del ptrbuffer [ : ] <EOL> code ( cline ) <EOL> def code ( stmt ) : <EOL> for line in stmt . splitlines ( ) : <EOL> codebuffer . append ( '<STR_LIT:U+0020>' * len ( stack ) + line . strip ( ) ) <EOL> for line in template . splitlines ( True ) : <EOL> lineno += <NUM_LIT:1> <EOL> line = touni ( line , self . encoding ) <EOL> sline = line . lstrip ( ) <EOL> if lineno <= <NUM_LIT:2> : <EOL> m = re . match ( r"<STR_LIT>" , sline ) <EOL> if m : self . encoding = m . group ( <NUM_LIT:1> ) <EOL> if m : line = line . replace ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> if sline and sline [ <NUM_LIT:0> ] == '<STR_LIT:%>' and sline [ : <NUM_LIT:2> ] != '<STR_LIT>' : <EOL> line = line . split ( '<STR_LIT:%>' , <NUM_LIT:1> ) [ <NUM_LIT:1> ] . lstrip ( ) <EOL> cline = self . split_comment ( line ) . strip ( ) <EOL> cmd = re . split ( r'<STR_LIT>' , cline ) [ <NUM_LIT:0> ] <EOL> flush ( ) <EOL> if cmd in self . blocks or multiline : <EOL> cmd = multiline or cmd <EOL> dedent = cmd in self . dedent_blocks <EOL> if dedent and not oneline and not multiline : <EOL> cmd = stack . pop ( ) <EOL> code ( line ) <EOL> oneline = not cline . endswith ( '<STR_LIT::>' ) <EOL> multiline = cmd if cline . endswith ( '<STR_LIT:\\>' ) else False <EOL> if not oneline and not multiline : <EOL> stack . append ( cmd ) <EOL> elif cmd == '<STR_LIT:end>' and stack : <EOL> code ( '<STR_LIT>' % ( stack . pop ( ) , line . strip ( ) [ <NUM_LIT:3> : ] ) ) <EOL> elif cmd == '<STR_LIT>' : <EOL> p = cline . split ( None , <NUM_LIT:2> ) [ <NUM_LIT:1> : ] <EOL> if len ( p ) == <NUM_LIT:2> : <EOL> code ( "<STR_LIT>" % ( repr ( p [ <NUM_LIT:0> ] ) , p [ <NUM_LIT:1> ] ) ) <EOL> elif p : <EOL> code ( "<STR_LIT>" % repr ( p [ <NUM_LIT:0> ] ) ) <EOL> else : <EOL> code ( "<STR_LIT>" ) <EOL> elif cmd == '<STR_LIT>' : <EOL> p = cline . split ( None , <NUM_LIT:2> ) [ <NUM_LIT:1> : ] <EOL> if len ( p ) == <NUM_LIT:2> : <EOL> code ( "<STR_LIT>" % ( repr ( p [ <NUM_LIT:0> ] ) , p [ <NUM_LIT:1> ] ) ) <EOL> elif p : <EOL> code ( "<STR_LIT>" % repr ( p [ <NUM_LIT:0> ] ) ) <EOL> else : <EOL> code ( line ) <EOL> else : <EOL> if line . strip ( ) . startswith ( '<STR_LIT>' ) : <EOL> line = line . replace ( '<STR_LIT>' , '<STR_LIT:%>' , <NUM_LIT:1> ) <EOL> ptrbuffer . append ( yield_tokens ( line ) ) <EOL> flush ( ) <EOL> return '<STR_LIT:\n>' . join ( codebuffer ) + '<STR_LIT:\n>' <EOL> def subtemplate ( self , _name , _stdout , * args , ** kwargs ) : <EOL> for dictarg in args : kwargs . update ( dictarg ) <EOL> if _name not in self . cache : <EOL> self . cache [ _name ] = self . __class__ ( name = _name , lookup = self . lookup ) <EOL> return self . cache [ _name ] . execute ( _stdout , kwargs ) <EOL> def execute ( self , _stdout , * args , ** kwargs ) : <EOL> for dictarg in args : kwargs . update ( dictarg ) <EOL> env = self . defaults . copy ( ) <EOL> env . update ( { '<STR_LIT>' : _stdout , '<STR_LIT>' : _stdout . extend , <EOL> '<STR_LIT>' : self . subtemplate , '<STR_LIT>' : self . _str , <EOL> '<STR_LIT>' : self . _escape , '<STR_LIT>' : env . get , <EOL> '<STR_LIT>' : env . setdefault , '<STR_LIT>' : env . __contains__ } ) <EOL> env . update ( kwargs ) <EOL> eval ( self . co , env ) <EOL> if '<STR_LIT>' in env : <EOL> subtpl , rargs = env [ '<STR_LIT>' ] <EOL> rargs [ '<STR_LIT>' ] = _stdout [ : ] <EOL> del _stdout [ : ] <EOL> return self . subtemplate ( subtpl , _stdout , rargs ) <EOL> return env <EOL> def render ( self , * args , ** kwargs ) : <EOL> """<STR_LIT>""" <EOL> for dictarg in args : kwargs . update ( dictarg ) <EOL> stdout = [ ] <EOL> self . execute ( stdout , kwargs ) <EOL> return '<STR_LIT>' . join ( stdout ) <EOL> def template ( * args , ** kwargs ) : <EOL> '''<STR_LIT>''' <EOL> tpl = args [ <NUM_LIT:0> ] if args else None <EOL> adapter = kwargs . pop ( '<STR_LIT>' , SimpleTemplate ) <EOL> lookup = kwargs . pop ( '<STR_LIT>' , TEMPLATE_PATH ) <EOL> tplid = ( id ( lookup ) , tpl ) <EOL> if tplid not in TEMPLATES or DEBUG : <EOL> settings = kwargs . pop ( '<STR_LIT>' , { } ) <EOL> if isinstance ( tpl , adapter ) : <EOL> TEMPLATES [ tplid ] = tpl <EOL> if settings : TEMPLATES [ tplid ] . prepare ( ** settings ) <EOL> elif "<STR_LIT:\n>" in tpl or "<STR_LIT:{>" in tpl or "<STR_LIT:%>" in tpl or '<STR_LIT:$>' in tpl : <EOL> TEMPLATES [ tplid ] = adapter ( source = tpl , lookup = lookup , ** settings ) <EOL> else : <EOL> TEMPLATES [ tplid ] = adapter ( name = tpl , lookup = lookup , ** settings ) <EOL> if not TEMPLATES [ tplid ] : <EOL> abort ( <NUM_LIT> , '<STR_LIT>' % tpl ) <EOL> for dictarg in args [ <NUM_LIT:1> : ] : kwargs . update ( dictarg ) <EOL> return TEMPLATES [ tplid ] . render ( kwargs ) <EOL> mako_template = functools . partial ( template , template_adapter = MakoTemplate ) <EOL> cheetah_template = functools . partial ( template , template_adapter = CheetahTemplate ) <EOL> jinja2_template = functools . partial ( template , template_adapter = Jinja2Template ) <EOL> def view ( tpl_name , ** defaults ) : <EOL> '''<STR_LIT>''' <EOL> def decorator ( func ) : <EOL> @ functools . wraps ( func ) <EOL> def wrapper ( * args , ** kwargs ) : <EOL> result = func ( * args , ** kwargs ) <EOL> if isinstance ( result , ( dict , DictMixin ) ) : <EOL> tplvars = defaults . copy ( ) <EOL> tplvars . update ( result ) <EOL> return template ( tpl_name , ** tplvars ) <EOL> elif result is None : <EOL> return template ( tpl_name , defaults ) <EOL> return result <EOL> return wrapper <EOL> return decorator <EOL> mako_view = functools . partial ( view , template_adapter = MakoTemplate ) <EOL> cheetah_view = functools . partial ( view , template_adapter = CheetahTemplate ) <EOL> jinja2_view = functools . partial ( view , template_adapter = Jinja2Template ) <EOL> TEMPLATE_PATH = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> TEMPLATES = { } <EOL> DEBUG = False <EOL> NORUN = False <EOL> HTTP_CODES = httplib . responses <EOL> HTTP_CODES [ <NUM_LIT> ] = "<STR_LIT>" <EOL> HTTP_CODES [ <NUM_LIT> ] = "<STR_LIT>" <EOL> HTTP_CODES [ <NUM_LIT> ] = "<STR_LIT>" <EOL> HTTP_CODES [ <NUM_LIT> ] = "<STR_LIT>" <EOL> HTTP_CODES [ <NUM_LIT> ] = "<STR_LIT>" <EOL> _HTTP_STATUS_LINES = dict ( ( k , '<STR_LIT>' % ( k , v ) ) for ( k , v ) in HTTP_CODES . items ( ) ) <EOL> ERROR_PAGE_TEMPLATE = """<STR_LIT>""" % __name__ <EOL> request = LocalRequest ( ) <EOL> response = LocalResponse ( ) <EOL> local = threading . local ( ) <EOL> app = default_app = AppStack ( ) <EOL> app . push ( ) <EOL> ext = _ImportRedirect ( '<STR_LIT>' if __name__ == '<STR_LIT:__main__>' else __name__ + "<STR_LIT>" , '<STR_LIT>' ) . module <EOL> if __name__ == '<STR_LIT:__main__>' : <EOL> opt , args , parser = _cmd_options , _cmd_args , _cmd_parser <EOL> if opt . version : <EOL> _stdout ( '<STR_LIT>' % __version__ ) <EOL> sys . exit ( <NUM_LIT:0> ) <EOL> if not args : <EOL> parser . print_help ( ) <EOL> _stderr ( '<STR_LIT>' ) <EOL> sys . exit ( <NUM_LIT:1> ) <EOL> sys . path . insert ( <NUM_LIT:0> , '<STR_LIT:.>' ) <EOL> sys . modules . setdefault ( '<STR_LIT>' , sys . modules [ '<STR_LIT:__main__>' ] ) <EOL> host , port = ( opt . bind or '<STR_LIT:localhost>' ) , <NUM_LIT> <EOL> if '<STR_LIT::>' in host : <EOL> host , port = host . rsplit ( '<STR_LIT::>' , <NUM_LIT:1> ) <EOL> run ( args [ <NUM_LIT:0> ] , host = host , port = port , server = opt . server , <EOL> reloader = opt . reload , plugins = opt . plugin , debug = opt . debug ) </s>
