?? __init__.py
字號:
"""A high-speed, production ready, thread pooled, generic WSGI server.Simplest example on how to use this module directly(without using CherryPy's application machinery): from cherrypy import wsgiserver def my_crazy_app(environ, start_response): status = '200 OK' response_headers = [('Content-type','text/plain')] start_response(status, response_headers) return ['Hello world!\n'] # Here we set our application to the script_name '/' wsgi_apps = [('/', my_crazy_app)] server = wsgiserver.CherryPyWSGIServer(('localhost', 8070), wsgi_apps, server_name='localhost') # Want SSL support? Just set these attributes # server.ssl_certificate = <filename> # server.ssl_private_key = <filename> if __name__ == '__main__': try: server.start() except KeyboardInterrupt: server.stop()This won't call the CherryPy engine (application side) at all, only theWSGI server, which is independant from the rest of CherryPy. Don'tlet the name "CherryPyWSGIServer" throw you; the name merely reflectsits origin, not it's coupling.The CherryPy WSGI server can serve as many WSGI applicationsas you want in one instance: wsgi_apps = [('/', my_crazy_app), ('/blog', my_blog_app)]"""import base64import Queueimport osimport requoted_slash = re.compile("(?i)%2F")import rfc822import sockettry: import cStringIO as StringIOexcept ImportError: import StringIOimport sysimport threadingimport timeimport tracebackfrom urllib import unquotefrom urlparse import urlparsetry: from OpenSSL import SSL from OpenSSL import cryptoexcept ImportError: SSL = Noneimport errnosocket_errors_to_ignore = []# Not all of these names will be defined for every platform.for _ in ("EPIPE", "ETIMEDOUT", "ECONNREFUSED", "ECONNRESET", "EHOSTDOWN", "EHOSTUNREACH", "WSAECONNABORTED", "WSAECONNREFUSED", "WSAECONNRESET", "WSAENETRESET", "WSAETIMEDOUT"): if _ in dir(errno): socket_errors_to_ignore.append(getattr(errno, _))# de-dupe the listsocket_errors_to_ignore = dict.fromkeys(socket_errors_to_ignore).keys()socket_errors_to_ignore.append("timed out")comma_separated_headers = ['ACCEPT', 'ACCEPT-CHARSET', 'ACCEPT-ENCODING', 'ACCEPT-LANGUAGE', 'ACCEPT-RANGES', 'ALLOW', 'CACHE-CONTROL', 'CONNECTION', 'CONTENT-ENCODING', 'CONTENT-LANGUAGE', 'EXPECT', 'IF-MATCH', 'IF-NONE-MATCH', 'PRAGMA', 'PROXY-AUTHENTICATE', 'TE', 'TRAILER', 'TRANSFER-ENCODING', 'UPGRADE', 'VARY', 'VIA', 'WARNING', 'WWW-AUTHENTICATE']class HTTPRequest(object): """An HTTP Request (and response). A single HTTP connection may consist of multiple request/response pairs. connection: the HTTP Connection object which spawned this request. rfile: the 'read' fileobject from the connection's socket ready: when True, the request has been parsed and is ready to begin generating the response. When False, signals the calling Connection that the response should not be generated and the connection should close. close_connection: signals the calling Connection that the request should close. This does not imply an error! The client and/or server may each request that the connection be closed. chunked_write: if True, output will be encoded with the "chunked" transfer-coding. This value is set automatically inside send_headers. """ def __init__(self, connection): self.connection = connection self.rfile = self.connection.rfile self.sendall = self.connection.sendall self.environ = connection.environ.copy() self.ready = False self.started_response = False self.status = "" self.outheaders = [] self.sent_headers = False self.close_connection = False self.chunked_write = False def parse_request(self): """Parse the next HTTP request start-line and message-headers.""" # HTTP/1.1 connections are persistent by default. If a client # requests a page, then idles (leaves the connection open), # then rfile.readline() will raise socket.error("timed out"). # Note that it does this based on the value given to settimeout(), # and doesn't need the client to request or acknowledge the close # (although your TCP stack might suffer for it: cf Apache's history # with FIN_WAIT_2). request_line = self.rfile.readline() if not request_line: # Force self.ready = False so the connection will close. self.ready = False return if request_line == "\r\n": # RFC 2616 sec 4.1: "...if the server is reading the protocol # stream at the beginning of a message and receives a CRLF # first, it should ignore the CRLF." # But only ignore one leading line! else we enable a DoS. request_line = self.rfile.readline() if not request_line: self.ready = False return server = self.connection.server environ = self.environ environ["SERVER_SOFTWARE"] = "%s WSGI Server" % server.version method, path, req_protocol = request_line.strip().split(" ", 2) environ["REQUEST_METHOD"] = method # path may be an abs_path (including "http://host.domain.tld"); scheme, location, path, params, qs, frag = urlparse(path) if frag: self.simple_response("400 Bad Request", "Illegal #fragment in Request-URI.") return if scheme: environ["wsgi.url_scheme"] = scheme if params: path = path + ";" + params # Unquote the path+params (e.g. "/this%20path" -> "this path"). # http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2 # # But note that "...a URI must be separated into its components # before the escaped characters within those components can be # safely decoded." http://www.ietf.org/rfc/rfc2396.txt, sec 2.4.2 atoms = [unquote(x) for x in quoted_slash.split(path)] path = "%2F".join(atoms) if path == "*": # This means, of course, that the last wsgi_app (shortest path) # will always handle a URI of "*". environ["SCRIPT_NAME"] = "" environ["PATH_INFO"] = "*" self.wsgi_app = server.mount_points[-1][1] else: for mount_point, wsgi_app in server.mount_points: # The mount_points list should be sorted by length, descending. if path.startswith(mount_point + "/") or path == mount_point: environ["SCRIPT_NAME"] = mount_point environ["PATH_INFO"] = path[len(mount_point):] self.wsgi_app = wsgi_app break else: self.simple_response("404 Not Found") return # Note that, like wsgiref and most other WSGI servers, # we unquote the path but not the query string. environ["QUERY_STRING"] = qs # Compare request and server HTTP protocol versions, in case our # server does not support the requested protocol. Limit our output # to min(req, server). We want the following output: # request server actual written supported response # protocol protocol response protocol feature set # a 1.0 1.0 1.0 1.0 # b 1.0 1.1 1.1 1.0 # c 1.1 1.0 1.0 1.0 # d 1.1 1.1 1.1 1.1 # Notice that, in (b), the response will be "HTTP/1.1" even though # the client only understands 1.0. RFC 2616 10.5.6 says we should # only return 505 if the _major_ version is different. rp = int(req_protocol[5]), int(req_protocol[7]) sp = int(server.protocol[5]), int(server.protocol[7]) if sp[0] != rp[0]: self.simple_response("505 HTTP Version Not Supported") return # Bah. "SERVER_PROTOCOL" is actually the REQUEST protocol. environ["SERVER_PROTOCOL"] = req_protocol # set a non-standard environ entry so the WSGI app can know what # the *real* server protocol is (and what features to support). # See http://www.faqs.org/rfcs/rfc2145.html. environ["ACTUAL_SERVER_PROTOCOL"] = server.protocol self.response_protocol = "HTTP/%s.%s" % min(rp, sp) # If the Request-URI was an absoluteURI, use its location atom. if location: environ["SERVER_NAME"] = location # then all the http headers try: self.read_headers() except ValueError, ex: self.simple_response("400 Bad Request", repr(ex.args)) return creds = environ.get("HTTP_AUTHORIZATION", "").split(" ", 1) environ["AUTH_TYPE"] = creds[0] if creds[0].lower() == 'basic': user, pw = base64.decodestring(creds[1]).split(":", 1) environ["REMOTE_USER"] = user # Persistent connection support if self.response_protocol == "HTTP/1.1": if environ.get("HTTP_CONNECTION", "") == "close": self.close_connection = True else: # HTTP/1.0 if environ.get("HTTP_CONNECTION", "") != "Keep-Alive": self.close_connection = True # Transfer-Encoding support te = None if self.response_protocol == "HTTP/1.1": te = environ.get("HTTP_TRANSFER_ENCODING") if te: te = [x.strip().lower() for x in te.split(",") if x.strip()] read_chunked = False if te: for enc in te: if enc == "chunked": read_chunked = True else: # Note that, even if we see "chunked", we must reject # if there is an extension we don't recognize. self.simple_response("501 Unimplemented") self.close_connection = True return if read_chunked: if not self.decode_chunked(): return # From PEP 333: # "Servers and gateways that implement HTTP 1.1 must provide # transparent support for HTTP 1.1's "expect/continue" mechanism. # This may be done in any of several ways: # 1. Respond to requests containing an Expect: 100-continue request # with an immediate "100 Continue" response, and proceed normally. # 2. Proceed with the request normally, but provide the application # with a wsgi.input stream that will send the "100 Continue" # response if/when the application first attempts to read from # the input stream. The read request must then remain blocked # until the client responds. # 3. Wait until the client decides that the server does not support # expect/continue, and sends the request body on its own. # (This is suboptimal, and is not recommended.) # # We used to do 3, but are now doing 1. Maybe we'll do 2 someday, # but it seems like it would be a big slowdown for such a rare case. if environ.get("HTTP_EXPECT", "") == "100-continue": self.simple_response(100) self.ready = True def read_headers(self): """Read header lines from the incoming stream.""" environ = self.environ while True: line = self.rfile.readline() if not line: # No more data--illegal end of headers raise ValueError("Illegal end of headers.") if line == '\r\n': # Normal end of headers break if line[0] in ' \t': # It's a continuation line. v = line.strip() else: k, v = line.split(":", 1) k, v = k.strip().upper(), v.strip() envname = "HTTP_" + k.replace("-", "_") if k in comma_separated_headers: existing = environ.get(envname) if existing: v = ", ".join((existing, v)) environ[envname] = v ct = environ.pop("HTTP_CONTENT_TYPE", None) if ct: environ["CONTENT_TYPE"] = ct cl = environ.pop("HTTP_CONTENT_LENGTH", None) if cl: environ["CONTENT_LENGTH"] = cl def decode_chunked(self): """Decode the 'chunked' transfer coding.""" cl = 0 data = StringIO.StringIO() while True: line = self.rfile.readline().strip().split(";", 1) chunk_size = int(line.pop(0), 16) if chunk_size <= 0: break## if line: chunk_extension = line[0] cl += chunk_size data.write(self.rfile.read(chunk_size)) crlf = self.rfile.read(2)
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -