1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
| class application: def run(self, middleware): return wsgi.runwsgi(self.wsgifunc(middleware))
def runwsgi(func): httpserver.runsimple(func, server_addr)
def runsimple(func, server_address=(“0.0.0.0”, 8080)): server = WSGIServer(server_address, func) server.start()
def WSGIServer(server_address, wsgi_app): import wsgiserver server = wsgiserver.CherryPyWSGIServer(server_address, wsgi_app, server_name=“localhost”) return server class CherryPyWSGIServer(HTTPServer): def init(self, bind_addr, wsgi_app, numthreads=10, server_name=None, max=-1, request_queue_size=5, timeout=10, shutdown_timeout=5): self.requests = ThreadPool(self, min=numthreads or 1, max=max) self.wsgi_app = wsgi_app self.gateway = wsgi_gateways[self.wsgi_version] class HTTPServer(object): def start(self): self.requests.start() self.ready = True while self.ready: self.tick() def tick(self): “””Accept a new connection and put it on the Queue.””” try: s, addr = self.socket.accept() … conn = self.ConnectionClass(self, s, makefile) self.requests.put(conn) class ThreadPool(object): def init(self, server, min=10, max=-1): self.server = server self.min = min self.max = max self._threads = [] self._queue = Queue.Queue() self.get = self._queue.get def start(self): “””Start the pool of threads.””” for i in range(self.min): self._threads.append(WorkerThread(self.server)) for worker in self._threads: worker.setName(“CP Server “ + worker.getName()) worker.start() def put(self, obj): self._queue.put(obj) if obj is _SHUTDOWNREQUEST: return
class WorkerThread(threading.Thread): def run(self): while True: conn = self.server.requests.get() conn.communicate()
class HTTPConnection(object): def communicate(self): while True: req = self.RequestHandlerClass(self.server, self) req.parse_request() req.respond() class HTTPRequest(object): def respond(self): self.server.gateway(self).respond()
class WSGIGateway_10(WSGIGateway): def init(self, req): self.req = req def respond(self): response = self.req.server.wsgi_app(self.env, self.start_response) for chunk in response: if chunk: if isinstance(chunk, unicode): chunk = chunk.encode(‘ISO-8859-1’) self.write(chunk)
class application: def wsgifunc(self, *middleware): def wsgi(env, start_resp): self.load(env) result = web.safestr(iter(result)) start_resp(status, headers) return itertools.chain(result, cleanup()) return wsgi
|