Mercurial > moin > 1.9
changeset 988:65dc979761f0
whitespace only and style changes
author | Thomas Waldmann <tw AT waldmann-edv DOT de> |
---|---|
date | Tue, 18 Jul 2006 12:55:53 +0200 |
parents | eaae4bcf60f3 |
children | 79e70c3cef6d |
files | MoinMoin/server/__init__.py MoinMoin/server/daemon.py MoinMoin/server/standalone.py MoinMoin/server/twistedmoin.py MoinMoin/server/wsgi.py |
diffstat | 5 files changed, 89 insertions(+), 87 deletions(-) [+] |
line wrap: on
line diff
--- a/MoinMoin/server/__init__.py Tue Jul 18 11:48:53 2006 +0200 +++ b/MoinMoin/server/__init__.py Tue Jul 18 12:55:53 2006 +0200 @@ -8,7 +8,6 @@ @license: GNU GPL, see COPYING for details. """ -# Imports import os @@ -46,13 +45,13 @@ This class does all error checking needed for config values, and will raise a RuntimeError on any fatal error. """ - + def __init__(self): """ Validate and post process configuration values Will raise RuntimeError for any wrong config value. """ - + # Check that docs path is accessible self.docs = os.path.normpath(os.path.abspath(self.docs)) if not os.access(self.docs, os.F_OK | os.R_OK | os.X_OK): @@ -63,7 +62,7 @@ if os.name == 'nt': self.uid = self.gid = 0 return - + # If serving privileged port, we must run as root to bind the port. # we will give up root privileges later if self.port < 1024 and os.getuid() != 0: @@ -86,4 +85,4 @@ except KeyError: raise RuntimeError("Unknown group: '%s', check group setting" % self.group) - +
--- a/MoinMoin/server/daemon.py Tue Jul 18 11:48:53 2006 +0200 +++ b/MoinMoin/server/daemon.py Tue Jul 18 12:55:53 2006 +0200 @@ -58,9 +58,9 @@ Represent a background process, which may be running or not. The process can be started, stopped, restarted or killed. - """ + """ commandPrefix = 'do_' - + def __init__(self, name, function, *args, **kw): """ Create a daemon @@ -75,7 +75,7 @@ self.args = args self.kw = kw self.pidFile = os.path.abspath(name + '.pid') - + # -------------------------------------------------------------------- # Commands @@ -115,21 +115,21 @@ """ running, pid = self.status() if not running: - return self.log("%s is not running" % self.name) + return self.log("%s is not running" % self.name) os.kill(pid, signal.SIGKILL) self.removePID() - + def do_restart(self): """ stop, wait until pid file gone and start again """ running, pid = self.status() if not running: self.log("%s is not running, trying to start" % self.name) else: - self.do_stop() + self.do_stop() timeoutSeconds = 2.0 start = time.time() while time.time() - start < timeoutSeconds: - running, pid = self.status() + running, pid = self.status() if not running: break time.sleep(0.1) @@ -177,7 +177,7 @@ self.warn("removing corrupted pid file: %s" % self.pidFile) self.removePID() return pid - + def daemonize(self): """ Make the current process a daemon @@ -189,19 +189,19 @@ if os.fork(): # launch child and... os._exit(0) # kill off parent again. os.umask(077) - null=os.open('/dev/null', os.O_RDWR) + null = os.open('/dev/null', os.O_RDWR) for i in range(3): try: os.dup2(null, i) except OSError, e: if e.errno != errno.EBADF: raise - os.close(null) + os.close(null) def writePID(self): pid = str(os.getpid()) open(self.pidFile, 'wb').write(pid) - + def removePID(self): try: os.remove(self.pidFile) @@ -229,7 +229,7 @@ if args == 1: self.usage('nothing to do') elif args > 2: - self.usage("too many arguments") + self.usage("too many arguments") try: command = sys.argv[1] func = getattr(self, self.commandPrefix + command) @@ -237,7 +237,7 @@ except AttributeError: self.usage('unknown command %r' % command) except Exception, why: - sys.exit("error: %s" % str(why)) + sys.exit("error: %s" % str(why)) def usage(self, message): sys.stderr.write('error: %s\n' % message) @@ -258,4 +258,7 @@ @copyright: 2004-2005 Thomas Waldmann, Nir Soffer @license: GNU GPL, see COPYING for details. -""" % {'name': self.name,} +""" % { + 'name': self.name, +} +
--- a/MoinMoin/server/standalone.py Tue Jul 18 11:48:53 2006 +0200 +++ b/MoinMoin/server/standalone.py Tue Jul 18 12:55:53 2006 +0200 @@ -52,9 +52,9 @@ This server is good for personal wiki, or when lowest memory footprint is needed. - """ + """ use_threads = False - + def __init__(self, config): self.htdocs = config.docs self.request_queue_size = config.requestQueueSize @@ -88,7 +88,7 @@ del req except socket.error, err: # Ignore certain errors - if err.args[0] not in [errno.EADDRNOTAVAIL,]: + if err.args[0] not in [errno.EADDRNOTAVAIL, ]: raise @@ -102,7 +102,7 @@ limit the load on the server. """ use_threads = True - + def __init__(self, config): self.thread_limit = config.threadLimit from threading import Condition @@ -127,7 +127,7 @@ t.start() finally: self.lock.release() - + def process_request_thread(self, request, client_address): """ Called for each request on a new thread @@ -162,7 +162,7 @@ remove the commented debug prints. """ use_threads = True - + def __init__(self, config): self.queue = [] # The size of the queue need more testing @@ -179,7 +179,7 @@ t = Thread(target=self.serve_forever_thread) t.start() SimpleServer.serve_forever(self) - + def process_request(self, request, client_address): """ Called for each request @@ -196,7 +196,7 @@ self.queue.insert(0, (request, client_address)) self.lock.notify() finally: - self.lock.release() + self.lock.release() def serve_forever_thread(self): """ The main loop of request threads @@ -209,9 +209,9 @@ self.finish_request(request, client_address) except: self.handle_error(request, client_address) - self.close_request(request) + self.close_request(request) # sys.stderr.write('thread exiting...\n') - + def pop_request(self): """ Pop a request from the queue @@ -232,8 +232,8 @@ finally: self.lock.release() # sys.stderr.write('thread exiting...\n') - sys.exit() - + sys.exit() + def die(self): """ Wake all threads then invoke base class die @@ -251,7 +251,7 @@ self.lock.notifyAll() finally: self.lock.release() - + class ForkingServer(SocketServer.ForkingMixIn, SimpleServer): """ Serve each request in a new process @@ -262,23 +262,23 @@ The mixin has its own process limit. """ max_children = 10 - - + + class MoinRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): bufferSize = 8 * 1024 # used to serve static files - staticExpire = 7 * 24 * 3600 # 1 week expiry for static files - + staticExpire = 7 * 24 * 3600 # 1 week expiry for static files + def __init__(self, request, client_address, server): self.server_version = "MoinMoin %s %s" % (version.revision, server.__class__.__name__) self.expires = 0 - SimpleHTTPServer.SimpleHTTPRequestHandler.__init__(self, request, + SimpleHTTPServer.SimpleHTTPRequestHandler.__init__(self, request, client_address, server) # ------------------------------------------------------------------- # do_METHOD dispatchers - called for each request - + def do_DIE(self): if self.server._abort: self.log_error("Shutting down") @@ -300,21 +300,21 @@ self.serve_static_file() else: self.serve_moin() - + do_POST = do_ALL do_GET = do_ALL do_HEAD = do_ALL # ------------------------------------------------------------------- # Serve methods - + def serve_static_file(self): """ Serve files from the htdocs directory """ self.expires = self.staticExpire path = self.path.split("?", 1) if len(path) > 1: self.path = path[0] # XXX ?params - + try: fn = getattr(SimpleHTTPServer.SimpleHTTPRequestHandler, 'do_' + self.command) fn(self) @@ -322,7 +322,7 @@ # Ignore certain errors if err.args[0] not in [errno.EPIPE, errno.ECONNABORTED]: raise - + def serve_moin(self): """ Serve a request using moin """ # don't make an Expires header for wiki pages @@ -335,7 +335,7 @@ # Ignore certain errors if err.args[0] not in [errno.EPIPE, errno.ECONNABORTED]: raise - + def translate_path(self, uri): """ Translate a /-separated PATH to the local filename syntax. @@ -361,7 +361,7 @@ if bad_uri: self.log_error("Detected bad request URI '%s', translated to '%s'" - % (uri, path,)) + % (uri, path,)) return path def end_headers(self): @@ -371,7 +371,7 @@ expires = now + self.expires self.send_header('Expires', timefuncs.formathttpdate(expires)) SimpleHTTPServer.SimpleHTTPRequestHandler.end_headers(self) - + def copyfile(self, source, outputfile): """Copy all data between two file objects. @@ -399,10 +399,10 @@ host = self.headers.get('Host', socket.gethostname()) path = self.path else: - host = '%s:%s' % (socket.gethostname(), + host = '%s:%s' % (socket.gethostname(), self.request.getsockname()[1]) path = '/' - + self.requestline = 'ERROR: Redirecting to https://%s%s' % (host, path) self.request_version = 'HTTP/1.1' self.command = 'GET' @@ -412,21 +412,21 @@ self.send_header('Connection', 'close') self.send_header('Content-Length', '0') self.wfile.write('\r\n') - + class SecureThreadPoolServer(TLSSocketServerMixIn, ThreadPoolServer): def __init__(self, config): ThreadPoolServer.__init__(self, config) - + cert = open(config.ssl_certificate).read() x509 = X509() x509.parse(cert) self.certChain = X509CertChain([x509]) - + priv = open(config.ssl_privkey).read() self.privateKey = parsePEMKey(priv, private=True) - + self.sessionCache = SessionCache() - + def finish_request(self, sock, client_address): # Peek into the packet, if it starts with GET or POS(T) then # redirect, otherwise let TLSLite handle the connection. @@ -435,25 +435,25 @@ SecureRequestRedirect(sock, client_address, self) return tls_connection = TLSConnection(sock) - if self.handshake(tls_connection) == True: + if self.handshake(tls_connection): self.RequestHandlerClass(tls_connection, client_address, self) else: # This will probably fail because the TLSConnection has # already written SSL stuff to the socket. But not sure what # else we should do. SecureRequestRedirect(sock, client_address, self) - + def handshake(self, tls_connection): try: - tls_connection.handshakeServer(certChain = self.certChain, - privateKey = self.privateKey, - sessionCache = self.sessionCache) + tls_connection.handshakeServer(certChain=self.certChain, + privateKey=self.privateKey, + sessionCache=self.sessionCache) tls_connection.ignoreAbruptClose = True return True except: return False - + def memoryProfileDecorator(func, profile): """ Return a profiled function """ def profiledFunction(*args, **kw): @@ -471,10 +471,10 @@ # Don't profile first request, its not interesting return func(*args, **kw) return profile.runcall(func, *args, **kw) - + return profiledFunction - + def quit(signo, stackframe): """ Signal handler for aborting signals """ global httpd @@ -508,14 +508,14 @@ except ImportError: serverClass = ForkingServer if serverClass is ForkingServer and not hasattr(os, "fork"): - serverClass = SimpleServer + serverClass = SimpleServer if serverClass.__name__ != config.serverClass: sys.stderr.write('%s is not available on this platform, falling back ' 'to %s\n' % (config.serverClass, serverClass.__name__)) - + from MoinMoin import config as _config - _config.use_threads = serverClass.use_threads + _config.use_threads = serverClass.use_threads return serverClass(config) # ------------------------------------------------------------------------ @@ -532,7 +532,7 @@ port = 8000 interface = 'localhost' logPath = None - + # Advanced options serverClass = 'ThreadPoolServer' threadLimit = 10 @@ -551,36 +551,36 @@ See StandaloneConfig for available options @param configClass: config class - """ + """ # Run only once! global httpd, config if httpd is not None: raise RuntimeError("You can run only one server per process!") - config = configClass() - + config = configClass() + # Install hotshot profiled serve_moin method. To compare with other # servers, we profile the part that create and run the request. if config.hotshotProfile: import hotshot config.hotshotProfile = hotshot.Profile(config.hotshotProfile) - MoinRequestHandler.serve_moin = hotshotProfileDecorator( + MoinRequestHandler.serve_moin = hotshotProfileDecorator( MoinRequestHandler.serve_moin, config.hotshotProfile) - + # Install a memory profiled serve_moin method if config.memoryProfile: config.memoryProfile.sample() MoinRequestHandler.serve_moin = memoryProfileDecorator( MoinRequestHandler.serve_moin, config.memoryProfile) - + if config.logPath: sys.stderr = file(config.logPath, 'at') registerSignalHandlers(quit) - httpd = makeServer(config) - + httpd = makeServer(config) + # Run as a safe user (posix only) if os.name == 'posix' and os.getuid() == 0: switchUID(config.uid, config.gid) - + httpd.serve_forever()
--- a/MoinMoin/server/twistedmoin.py Tue Jul 18 11:48:53 2006 +0200 +++ b/MoinMoin/server/twistedmoin.py Tue Jul 18 12:55:53 2006 +0200 @@ -21,7 +21,6 @@ @license: GNU GPL, see COPYING for details. """ -# Twisted imports from twisted.application import internet, service from twisted.web import script, static, server, vhost, resource, util from twisted.internet import threads, reactor @@ -47,18 +46,18 @@ # Server globals config = None - + class WikiResource(resource.Resource): """ Wiki resource """ isLeaf = 1 - + def render(self, request): return server.NOT_DONE_YET class WikiRoot(resource.Resource): """ Wiki root resource """ - + def getChild(self, name, request): # Serve images and css from '/wiki' if request.prepath == [] and name == 'wiki': @@ -112,8 +111,8 @@ filenames of file uploads ( FIELDNAME__filename__ ). """ import cgi - - self.content.seek(0,0) + + self.content.seek(0, 0) self.args = {} self.extended_args = {} self.stack = [] @@ -169,7 +168,7 @@ if i.filename: args[key + '__filename__'] = i.filename args[key] = fixedResult - + self.process() @@ -193,7 +192,7 @@ """ Cleaup before stoping """ server.Site.stopFactory(self) if config.hotshotProfile: - config.hotshotProfile.close() + config.hotshotProfile.close() class TwistedConfig(Config): @@ -211,9 +210,9 @@ virtualHosts = None memoryProfile = None hotshotProfile = None - + # sslcert = ('/whereever/cert/sitekey.pem', '/whereever/cert/sitecert.pem') - sslcert = None + sslcert = None def __init__(self): Config.__init__(self) @@ -235,10 +234,10 @@ # Create config instance (raise RuntimeError if config invalid) global config config = ConfigClass() - + # Set number of threads reactor.suggestThreadPoolSize(config.threads) - + # The root of the HTTP hierarchy default = WikiRoot() @@ -268,10 +267,10 @@ interface, port = entry.split(':', 1) except ValueError: interface, port = entry, config.port - + # Might raise ValueError if not integer. # TODO: check if we can use string port, like 'http' - port = int(port) + port = int(port) if port == 443 and ssl and ssl.supported and config.sslcert: sslContext = ssl.DefaultOpenSSLContextFactory(*config.sslcert)