home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2010 November / maximum-cd-2010-11.iso / DiscContents / calibre-0.7.13.msi / file_1491 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-08-06  |  7.8 KB  |  264 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. import logging
  5. import StringIO
  6. import cherrypy
  7. from cherrypy._cperror import format_exc, bare_error
  8. from cherrypy.lib import http
  9.  
  10. def setup(req):
  11.     apache = apache
  12.     import mod_python
  13.     options = req.get_options()
  14.     if 'cherrypy.setup' in options:
  15.         atoms = options['cherrypy.setup'].split('::', 1)
  16.         if len(atoms) == 1:
  17.             mod = __import__(atoms[0], globals(), locals())
  18.         else:
  19.             (modname, fname) = atoms
  20.             mod = __import__(modname, globals(), locals(), [
  21.                 fname])
  22.             func = getattr(mod, fname)
  23.             func()
  24.     
  25.     cherrypy.config.update({
  26.         'log.screen': False,
  27.         'tools.ignore_headers.on': True,
  28.         'tools.ignore_headers.headers': [
  29.             'Range'] })
  30.     engine = cherrypy.engine
  31.     if hasattr(engine, 'signal_handler'):
  32.         engine.signal_handler.unsubscribe()
  33.     
  34.     if hasattr(engine, 'console_control_handler'):
  35.         engine.console_control_handler.unsubscribe()
  36.     
  37.     engine.autoreload.unsubscribe()
  38.     cherrypy.server.unsubscribe()
  39.     
  40.     def _log(msg, level):
  41.         newlevel = apache.APLOG_ERR
  42.         if logging.DEBUG >= level:
  43.             newlevel = apache.APLOG_DEBUG
  44.         elif logging.INFO >= level:
  45.             newlevel = apache.APLOG_INFO
  46.         elif logging.WARNING >= level:
  47.             newlevel = apache.APLOG_WARNING
  48.         
  49.         apache.log_error(msg, newlevel, req.server)
  50.  
  51.     engine.subscribe('log', _log)
  52.     engine.start()
  53.     
  54.     def cherrypy_cleanup(data):
  55.         engine.exit()
  56.  
  57.     
  58.     try:
  59.         apache.register_cleanup(cherrypy_cleanup)
  60.     except AttributeError:
  61.         ((None, None),)
  62.         ((None, None),)
  63.         req.server.register_cleanup(req, cherrypy_cleanup)
  64.     except:
  65.         ((None, None),)
  66.  
  67.  
  68.  
  69. class _ReadOnlyRequest:
  70.     expose = ('read', 'readline', 'readlines')
  71.     
  72.     def __init__(self, req):
  73.         for method in self.expose:
  74.             self.__dict__[method] = getattr(req, method)
  75.         
  76.  
  77.  
  78. recursive = False
  79. _isSetUp = False
  80.  
  81. def handler(req):
  82.     global _isSetUp
  83.     apache = apache
  84.     import mod_python
  85.     
  86.     try:
  87.         if not _isSetUp:
  88.             setup(req)
  89.             _isSetUp = True
  90.         
  91.         local = req.connection.local_addr
  92.         if not req.connection.local_host:
  93.             pass
  94.         local = http.Host(local[0], local[1], '')
  95.         remote = req.connection.remote_addr
  96.         if not req.connection.remote_host:
  97.             pass
  98.         remote = http.Host(remote[0], remote[1], '')
  99.         if not req.parsed_uri[0]:
  100.             pass
  101.         scheme = 'http'
  102.         req.get_basic_auth_pw()
  103.         
  104.         try:
  105.             q = apache.mpm_query
  106.             threaded = q(apache.AP_MPMQ_IS_THREADED)
  107.             forked = q(apache.AP_MPMQ_IS_FORKED)
  108.         except AttributeError:
  109.             bad_value = "You must provide a PythonOption '%s', either 'on' or 'off', when running a version of mod_python < 3.1"
  110.             threaded = options.get('multithread', '').lower()
  111.             if threaded == 'on':
  112.                 threaded = True
  113.             elif threaded == 'off':
  114.                 threaded = False
  115.             else:
  116.                 raise ValueError(bad_value % 'multithread')
  117.             forked = (threaded == 'on').get('multiprocess', '').lower()
  118.             if forked == 'on':
  119.                 forked = True
  120.             elif forked == 'off':
  121.                 forked = False
  122.             else:
  123.                 raise ValueError(bad_value % 'multiprocess')
  124.             forked == 'on'
  125.  
  126.         if not req.uri:
  127.             pass
  128.         sn = cherrypy.tree.script_name('/')
  129.         if sn is None:
  130.             send_response(req, '404 Not Found', [], '')
  131.         else:
  132.             app = cherrypy.tree.apps[sn]
  133.             method = req.method
  134.             path = req.uri
  135.             if not req.args:
  136.                 pass
  137.             qs = ''
  138.             reqproto = req.protocol
  139.             headers = req.headers_in.items()
  140.             rfile = _ReadOnlyRequest(req)
  141.             prev = None
  142.             
  143.             try:
  144.                 redirections = []
  145.                 while True:
  146.                     (request, response) = app.get_serving(local, remote, scheme, 'HTTP/1.1')
  147.                     request.login = req.user
  148.                     request.multithread = bool(threaded)
  149.                     request.multiprocess = bool(forked)
  150.                     request.app = app
  151.                     request.prev = prev
  152.                     
  153.                     try:
  154.                         request.run(method, path, qs, reqproto, headers, rfile)
  155.                     continue
  156.                     except cherrypy.InternalRedirect:
  157.                         ir = None
  158.                         app.release_serving()
  159.                         prev = request
  160.                         if not recursive:
  161.                             if ir.path in redirections:
  162.                                 raise RuntimeError('InternalRedirector visited the same URL twice: %r' % ir.path)
  163.                             ir.path in redirections
  164.                             if qs:
  165.                                 qs = '?' + qs
  166.                             
  167.                             redirections.append(sn + path + qs)
  168.                         
  169.                         method = 'GET'
  170.                         path = ir.path
  171.                         qs = ir.query_string
  172.                         rfile = StringIO.StringIO()
  173.                         continue
  174.                     
  175.  
  176.                     None<EXCEPTION MATCH>cherrypy.InternalRedirect
  177.                 send_response(req, response.status, response.header_list, response.body, response.stream)
  178.             finally:
  179.                 app.release_serving()
  180.  
  181.     except:
  182.         tb = format_exc()
  183.         cherrypy.log(tb, 'MOD_PYTHON', severity = logging.ERROR)
  184.         (s, h, b) = bare_error()
  185.         send_response(req, s, h, b)
  186.  
  187.     return apache.OK
  188.  
  189.  
  190. def send_response(req, status, headers, body, stream = False):
  191.     req.status = int(status[:3])
  192.     req.content_type = 'text/plain'
  193.     for header, value in headers:
  194.         if header.lower() == 'content-type':
  195.             req.content_type = value
  196.             continue
  197.         
  198.         req.headers_out.add(header, value)
  199.     
  200.     if stream:
  201.         req.flush()
  202.     
  203.     if isinstance(body, basestring):
  204.         req.write(body)
  205.     else:
  206.         for seg in body:
  207.             req.write(seg)
  208.         
  209.  
  210. import os
  211. import re
  212.  
  213. def read_process(cmd, args = ''):
  214.     (pipein, pipeout) = os.popen4('%s %s' % (cmd, args))
  215.     
  216.     try:
  217.         firstline = pipeout.readline()
  218.         if re.search('(not recognized|No such file|not found)', firstline, re.IGNORECASE):
  219.             raise IOError('%s must be on your system path.' % cmd)
  220.         re.search('(not recognized|No such file|not found)', firstline, re.IGNORECASE)
  221.         output = firstline + pipeout.read()
  222.     finally:
  223.         pipeout.close()
  224.  
  225.     return output
  226.  
  227.  
  228. class ModPythonServer(object):
  229.     template = '\n# Apache2 server configuration file for running CherryPy with mod_python.\n\nDocumentRoot "/"\nListen %(port)s\nLoadModule python_module modules/mod_python.so\n\n<Location %(loc)s>\n    SetHandler python-program\n    PythonHandler %(handler)s\n    PythonDebug On\n%(opts)s\n</Location>\n'
  230.     
  231.     def __init__(self, loc = '/', port = 80, opts = None, apache_path = 'apache', handler = 'cherrypy._cpmodpy::handler'):
  232.         self.loc = loc
  233.         self.port = port
  234.         self.opts = opts
  235.         self.apache_path = apache_path
  236.         self.handler = handler
  237.  
  238.     
  239.     def start(self):
  240.         opts = []([ '    PythonOption %s %s\n' % (k, v) for k, v in self.opts ])
  241.         conf_data = self.template % {
  242.             'port': self.port,
  243.             'loc': self.loc,
  244.             'opts': opts,
  245.             'handler': self.handler }
  246.         mpconf = os.path.join(os.path.dirname(__file__), 'cpmodpy.conf')
  247.         f = open(mpconf, 'wb')
  248.         
  249.         try:
  250.             f.write(conf_data)
  251.         finally:
  252.             f.close()
  253.  
  254.         response = read_process(self.apache_path, '-k start -f %s' % mpconf)
  255.         self.ready = True
  256.         return response
  257.  
  258.     
  259.     def stop(self):
  260.         os.popen('apache -k stop')
  261.         self.ready = False
  262.  
  263.  
  264.