"""CherryPy is a pythonic, object-oriented HTTP framework.CherryPy consists of not one, but four separate API layers.The APPLICATION LAYER is the simplest. CherryPy applications are written asa tree of classes and methods, where each branch in the tree corresponds toa branch in the URL path. Each method is a 'page handler', which receivesGET and POST params as keyword arguments, and returns or yields the (HTML)body of the response. The special method name 'index' is used for pathsthat end in a slash, and the special method name 'default' is used tohandle multiple paths via a single handler. This layer also includes: * the 'exposed' attribute (and cherrypy.expose) * cherrypy.quickstart() * _cp_config attributes * cherrypy.tools (including cherrypy.session) * cherrypy.url()The ENVIRONMENT LAYER is used by developers at all levels. It providesinformation about the current request and response, plus the applicationand server environment, via a (default) set of top-level objects: * cherrypy.request * cherrypy.response * cherrypy.engine * cherrypy.server * cherrypy.tree * cherrypy.config * cherrypy.thread_data * cherrypy.log * cherrypy.HTTPError, NotFound, and HTTPRedirect * cherrypy.libThe EXTENSION LAYER allows advanced users to construct and share their ownplugins. It consists of: * Hook API * Tool API * Toolbox API * Dispatch API * Config Namespace APIFinally, there is the CORE LAYER, which uses the core API's to constructthe default components which are available at higher layers. You can thinkof the default components as the 'reference implementation' for CherryPy.Megaframeworks (and advanced users) may replace the default componentswith customized or extended components. The core API's are: * Application API * Engine API * Request API * Server API * WSGI APIThese API's are described in the CherryPy specification:http://www.cherrypy.org/wiki/CherryPySpec"""__version__="3.1.0beta3"fromurlparseimporturljoinas_urljoinclass_AttributeDocstrings(type):"""Metaclass for declaring docstrings for class attributes."""# The full docstring for this type is down in the __init__ method so# that it doesn't show up in help() for every consumer class.def__init__(cls,name,bases,dct):'''Metaclass for declaring docstrings for class attributes. Base Python doesn't provide any syntax for setting docstrings on 'data attributes' (non-callables). This metaclass allows class definitions to follow the declaration of a data attribute with a docstring for that attribute; the attribute docstring will be popped from the class dict and folded into the class docstring. The naming convention for attribute docstrings is: <attrname> + "__doc". For example: class Thing(object): """A thing and its properties.""" __metaclass__ = cherrypy._AttributeDocstrings height = 50 height__doc = """The height of the Thing in inches.""" In which case, help(Thing) starts like this: >>> help(mod.Thing) Help on class Thing in module pkg.mod: class Thing(__builtin__.object) | A thing and its properties. | | height [= 50]: | The height of the Thing in inches. | The benefits of this approach over hand-edited class docstrings: 1. Places the docstring nearer to the attribute declaration. 2. Makes attribute docs more uniform ("name (default): doc"). 3. Reduces mismatches of attribute _names_ between the declaration and the documentation. 4. Reduces mismatches of attribute default _values_ between the declaration and the documentation. The benefits of a metaclass approach over other approaches: 1. Simpler ("less magic") than interface-based solutions. 2. __metaclass__ can be specified at the module global level for classic classes. For various formatting reasons, you should write multiline docs with a leading newline and not a trailing one: response__doc = """ The response object for the current thread. In the main thread, and any threads which are not HTTP requests, this is None.""" The type of the attribute is intentionally not included, because that's not How Python Works. Quack. '''newdoc=[cls.__doc__or""]dctnames=dct.keys()dctnames.sort()fornameindctnames:ifname.endswith("__doc"):# Remove the magic doc attribute.ifhasattr(cls,name):delattr(cls,name)# Get an inspect-style docstring if possible (usually so).val=dct[name]try:importinspectval=inspect.getdoc(property(doc=val)).strip()except:pass# Indent the docstring.val='\n'.join([' '+line.rstrip()forlineinval.split('\n')])# Get the default value.attrname=name[:-5]try:attrval=getattr(cls,attrname)exceptAttributeError:attrval="missing"# Add the complete attribute docstring to our list.newdoc.append("%s [= %r]:\n%s"%(attrname,attrval,val))# Add our list of new docstrings to the class docstring.cls.__doc__="\n\n".join(newdoc)fromcherrypy._cperrorimportHTTPError,HTTPRedirect,InternalRedirectfromcherrypy._cperrorimportNotFound,CherryPyException,TimeoutErrorfromcherrypyimport_cpdispatchasdispatchfromcherrypyimport_cptoolstools=_cptools.default_toolboxTool=_cptools.Toolfromcherrypyimport_cprequestfromcherrypy.libimporthttpas_httpfromcherrypyimport_cptreetree=_cptree.Tree()fromcherrypy._cptreeimportApplicationfromcherrypyimport_cpwsgiaswsgifromcherrypyimportrestsrvtry:fromcherrypy.restsrvimportwin32as_restsrvwinengine=_restsrvwin.Win32Bus()_console_control_handler=_restsrvwin.ConsoleCtrlHandler(engine)# If you don't want a ConsoleControlHandler,# unsubscribe this before calling engine.start()._console_control_handler.subscribe()exceptImportError:engine=restsrv.bus# Timeout monitorclass_TimeoutMonitor(restsrv.plugins.Monitor):def__init__(self,bus):self.servings=[]restsrv.plugins.Monitor.__init__(self,bus,self.run)defacquire(self):self.servings.append((serving.request,serving.response))defrelease(self):try:self.servings.remove((serving.request,serving.response))exceptValueError:passdefrun(self):"""Check timeout on all responses. (Internal)"""forreq,respinself.servings:resp.check_timeout()timeout_monitor=_TimeoutMonitor(engine)timeout_monitor.subscribe()# Add an autoreloader (the 'engine' config namespace may detach/attach it).engine.autoreload=restsrv.plugins.Autoreloader(engine)engine.autoreload.subscribe()restsrv.plugins.ThreadManager(engine).subscribe()signal_handler=restsrv.plugins.SignalHandler(engine)fromcherrypyimport_cpserverserver=_cpserver.Server()server.subscribe()defquickstart(root=None,script_name="",config=None):"""Mount the given root, start the builtin server (and engine), then block. root: an instance of a "controller class" (a collection of page handler methods) which represents the root of the application. script_name: a string containing the "mount point" of the application. This should start with a slash, and be the path portion of the URL at which to mount the given root. For example, if root.index() will handle requests to "http://www.example.com:8080/dept/app1/", then the script_name argument would be "/dept/app1". It MUST NOT end in a slash. If the script_name refers to the root of the URI, it MUST be an empty string (not "/"). config: a file or dict containing application config. If this contains a [global] section, those entries will be used in the global (site-wide) config. """ifconfig:_global_conf_alias.update(config)ifrootisnotNone:tree.mount(root,script_name,config)signal_handler.subscribe()engine.start()engine.block()try:fromthreadingimportlocalas_localexceptImportError:fromcherrypy._cpthreadinglocalimportlocalas_localclass_Serving(_local):"""An interface for registering request and response objects. Rather than have a separate "thread local" object for the request and the response, this class works as a single threadlocal container for both objects (and any others which developers wish to define). In this way, we can easily dump those objects when we stop/start a new HTTP conversation, yet still refer to them as module-level globals in a thread-safe way. """__metaclass__=_AttributeDocstringsrequest=_cprequest.Request(_http.Host("127.0.0.1",80),_http.Host("127.0.0.1",1111))request__doc=""" The request object for the current thread. In the main thread, and any threads which are not receiving HTTP requests, this is None."""response=_cprequest.Response()response__doc=""" The response object for the current thread. In the main thread, and any threads which are not receiving HTTP requests, this is None."""defload(self,request,response):self.request=requestself.response=responsedefclear(self):"""Remove all attributes of self."""self.__dict__.clear()serving=_Serving()class_ThreadLocalProxy(object):__slots__=['__attrname__','__dict__']def__init__(self,attrname):self.__attrname__=attrnamedef__getattr__(self,name):child=getattr(serving,self.__attrname__)returngetattr(child,name)def__setattr__(self,name,value):ifnamein("__attrname__",):object.__setattr__(self,name,value)else:child=getattr(serving,self.__attrname__)setattr(child,name,value)def__delattr__(self,name):child=getattr(serving,self.__attrname__)delattr(child,name)def_get_dict(self):child=getattr(serving,self.__attrname__)d=child.__class__.__dict__.copy()d.update(child.__dict__)returnd__dict__=property(_get_dict)def__getitem__(self,key):child=getattr(serving,self.__attrname__)returnchild[key]def__setitem__(self,key,value):child=getattr(serving,self.__attrname__)child[key]=valuedef__delitem__(self,key):child=getattr(serving,self.__attrname__)delchild[key]def__contains__(self,key):child=getattr(serving,self.__attrname__)returnkeyinchild# Create request and response object (the same objects will be used# throughout the entire life of the webserver, but will redirect# to the "serving" object)request=_ThreadLocalProxy('request')response=_ThreadLocalProxy('response')# Create thread_data object as a thread-specific all-purpose storageclass_ThreadData(_local):"""A container for thread-specific data."""thread_data=_ThreadData()# Monkeypatch pydoc to allow help() to go through the threadlocal proxy.# Jan 2007: no Googleable examples of anyone else replacing pydoc.resolve.# The only other way would be to change what is returned from type(request)# and that's not possible in pure Python (you'd have to fake ob_type).def_cherrypy_pydoc_resolve(thing,forceload=0):"""Given an object or a path to an object, get the object and its name."""ifisinstance(thing,_ThreadLocalProxy):thing=getattr(serving,thing.__attrname__)return_pydoc._builtin_resolve(thing,forceload)try:importpydocas_pydoc_pydoc._builtin_resolve=_pydoc.resolve_pydoc.resolve=_cherrypy_pydoc_resolveexceptImportError:passfromcherrypyimport_cploggingclass_GlobalLogManager(_cplogging.LogManager):def__call__(self,*args,**kwargs):try:log=request.app.logexceptAttributeError:log=selfreturnlog.error(*args,**kwargs)defaccess(self):try:returnrequest.app.log.access()exceptAttributeError:return_cplogging.LogManager.access(self)log=_GlobalLogManager()# Set a default screen handler on the global log.log.screen=Truelog.error_file=''# Using an access file makes CP about 10% slower. Leave off by default.log.access_file=''def_buslog(msg):log.error(msg,'ENGINE')engine.subscribe('log',_buslog)# Helper functions for CP apps #defexpose(func=None,alias=None):"""Expose the function, optionally providing an alias or set of aliases."""defexpose_(func):func.exposed=TrueifaliasisnotNone:ifisinstance(alias,basestring):parents[alias.replace(".","_")]=funcelse:forainalias:parents[a.replace(".","_")]=funcreturnfuncimportsys,typesifisinstance(func,(types.FunctionType,types.MethodType)):# expose is being called directly, before the method has been boundparents=sys._getframe(1).f_localsreturnexpose_(func)else:ifaliasisNone:# expose is being called as a decorator "@expose"func.exposed=Truereturnfuncelse:# expose is returning a decorator "@expose(alias=...)"parents=sys._getframe(1).f_localsreturnexpose_defurl(path="",qs="",script_name=None,base=None,relative=None):"""Create an absolute URL for the given path. If 'path' starts with a slash ('/'), this will return (base + script_name + path + qs). If it does not start with a slash, this returns (base + script_name [+ request.path_info] + path + qs). If script_name is None, cherrypy.request will be used to find a script_name, if available. If base is None, cherrypy.request.base will be used (if available). Note that you can use cherrypy.tools.proxy to change this. Finally, note that this function can be used to obtain an absolute URL for the current request path (minus the querystring) by passing no args. If you call url(qs=cherrypy.request.query_string), you should get the original browser URL (assuming no internal redirections). If relative is None or not provided, request.app.relative_urls will be used (if available, else False). If False, the output will be an absolute URL (including the scheme, host, vhost, and script_name). If True, the output will instead be a URL that is relative to the current request path, perhaps including '..' atoms. If relative is the string 'server', the output will instead be a URL that is relative to the server root; i.e., it will start with a slash. """ifqs:qs='?'+qsifrequest.app:ifnotpath.startswith("/"):# Append/remove trailing slash from path_info as needed# (this is to support mistyped URL's without redirecting;# if you want to redirect, use tools.trailing_slash).pi=request.path_infoifrequest.is_indexisTrue:ifnotpi.endswith('/'):pi=pi+'/'elifrequest.is_indexisFalse:ifpi.endswith('/')andpi!='/':pi=pi[:-1]ifpath=="":path=pielse:path=_urljoin(pi,path)ifscript_nameisNone:script_name=request.script_nameifbaseisNone:base=request.basenewurl=base+script_name+path+qselse:# No request.app (we're being called outside a request).# We'll have to guess the base from server.* attributes.# This will produce very different results from the above# if you're using vhosts or tools.proxy.ifbaseisNone:base=server.base()path=(script_nameor"")+pathnewurl=base+path+qsif'./'innewurl:# Normalize the URL by removing ./ and ../atoms=[]foratominnewurl.split('/'):ifatom=='.':passelifatom=='..':atoms.pop()else:atoms.append(atom)newurl='/'.join(atoms)# At this point, we should have a fully-qualified absolute URL.ifrelativeisNone:relative=getattr(request.app,"relative_urls",False)# See http://www.ietf.org/rfc/rfc2396.txtifrelative=='server':# "A relative reference beginning with a single slash character is# termed an absolute-path reference, as defined by <abs_path>..."# This is also sometimes called "server-relative".newurl='/'+'/'.join(newurl.split('/',3)[3:])elifrelative:# "A relative reference that does not begin with a scheme name# or a slash character is termed a relative-path reference."old=url().split('/')[:-1]new=newurl.split('/')whileoldandnew:a,b=old[0],new[0]ifa!=b:breakold.pop(0)new.pop(0)new=(['..']*len(old))+newnewurl='/'.join(new)returnnewurl# import _cpconfig last so it can reference other top-level objectsfromcherrypyimport_cpconfig# Use _global_conf_alias so quickstart can use 'config' as an arg# without shadowing cherrypy.config.config=_global_conf_alias=_cpconfig.Config()fromcherrypyimport_cpcheckerchecker=_cpchecker.Checker()engine.subscribe('start',checker)