# -*- coding: utf-8 -*- '''mpcp - mod_python serves CherryPy Jamie Turner (jamie polimetrix com) ''' import cherrypy, sys, time assert not cherrypy.__version__.startswith('2.1'), \ "This version of mpcp requires cherrypy 2.2+" from mod_python import apache, Session import logging log = logging.getLogger("webapp") _isSetUp = False def setup(req, options): global _isSetUp if _isSetUp: return # add optional sys paths path = options['sys.path'] if path is not None: sys.path.insert( 0, path ) # call CP root class modname, fname = options['cherrysetup'].split('::') mod = __import__(modname, globals(), locals(), [fname]) func = getattr(mod, fname) func() cherrypy.config.update({'global' : {'server.log_to_screen' : False}}) cherrypy.server.start(init_only=True, server_class=None) _isSetUp = True req.server.register_cleanup(req, cherrypy_cleanup) def cherrypy_cleanup(_dc): cherrypy.server.stop() class _ReadOnlyRequest: expose = ('read', 'readline', 'readlines') def __init__(self, req): for method in self.expose: self.__dict__[method] = getattr(req, method) def handler(req): config = req.get_config() options = req.get_options() setup(req, options) # Basic vars needed by CherryPy for request handling clientAddress = req.connection.remote_addr remoteHost = clientAddress[0] scheme = req.parsed_uri[0] or 'http' request = cherrypy.server.request(clientAddress, remoteHost, scheme) requestLine = req.the_request headers = req.headers_in.items() rfile = _ReadOnlyRequest(req) # Information to populate the request req.get_basic_auth_pw() request.login = req.user if apache.mpm_query(apache.AP_MPMQ_IS_THREADED): request.multithread = True else: request.multithread = False if apache.mpm_query(apache.AP_MPMQ_IS_FORKED): request.multiprocess = True else: request.multiprocess = False # Let CherryPy handle the request and generate the response response = request.run(requestLine, headers, rfile) # Translate and send the response back to the client ret = sendResponse(req, response) request.close() return ret def sendResponse(req, response): # Headers req.content_type = "text/plain" gmt_expiration_time = time.gmtime(time.time() + (6000 * 6000)) expireTime = time.strftime("%a, %d-%b-%Y %H:%M:%S GMT", gmt_expiration_time) gmt_session_time = time.gmtime(time.time() + (600 * 600)) expireSessionTime = time.strftime("%a, %d-%b-%Y %H:%M:%S GMT", gmt_session_time) for header, value in response.header_list: if header.lower() == 'content-type': req.content_type = value continue tv = type(value) if tv in (list, tuple): for subval in value: req.headers_out.add(header, value) elif tv is str: req.headers_out.add(header,value) # Cookie cook_out = response.simple_cookie.output() if cook_out: for line in cook_out.split('\n'): req.headers_out.add(*tuple(v.strip() for v in line.split(':',1))) rv = int(response.status[:3]) req.status = rv # Body if type(response.body) is str: req.write(response.body) else: for seg in response.body: req.write(seg) return apache.OK