ยปCore Development>Code coverage>Lib/wsgiref/simple_server.py

Python code coverage for Lib/wsgiref/simple_server.py

#countcontent
1n/a"""BaseHTTPServer that implements the Python WSGI protocol (PEP 3333)
2n/a
3n/aThis is both an example of how WSGI can be implemented, and a basis for running
4n/asimple web applications on a local machine, such as might be done when testing
5n/aor debugging an application. It has not been reviewed for security issues,
6n/ahowever, and we strongly recommend that you use a "real" web server for
7n/aproduction use.
8n/a
9n/aFor example usage, see the 'if __name__=="__main__"' block at the end of the
10n/amodule. See also the BaseHTTPServer module docs for other API information.
11n/a"""
12n/a
13n/afrom http.server import BaseHTTPRequestHandler, HTTPServer
14n/aimport sys
15n/aimport urllib.parse
16n/afrom wsgiref.handlers import SimpleHandler
17n/afrom platform import python_implementation
18n/a
19n/a__version__ = "0.2"
20n/a__all__ = ['WSGIServer', 'WSGIRequestHandler', 'demo_app', 'make_server']
21n/a
22n/a
23n/aserver_version = "WSGIServer/" + __version__
24n/asys_version = python_implementation() + "/" + sys.version.split()[0]
25n/asoftware_version = server_version + ' ' + sys_version
26n/a
27n/a
28n/aclass ServerHandler(SimpleHandler):
29n/a
30n/a server_software = software_version
31n/a
32n/a def close(self):
33n/a try:
34n/a self.request_handler.log_request(
35n/a self.status.split(' ',1)[0], self.bytes_sent
36n/a )
37n/a finally:
38n/a SimpleHandler.close(self)
39n/a
40n/a
41n/a
42n/aclass WSGIServer(HTTPServer):
43n/a
44n/a """BaseHTTPServer that implements the Python WSGI protocol"""
45n/a
46n/a application = None
47n/a
48n/a def server_bind(self):
49n/a """Override server_bind to store the server name."""
50n/a HTTPServer.server_bind(self)
51n/a self.setup_environ()
52n/a
53n/a def setup_environ(self):
54n/a # Set up base environment
55n/a env = self.base_environ = {}
56n/a env['SERVER_NAME'] = self.server_name
57n/a env['GATEWAY_INTERFACE'] = 'CGI/1.1'
58n/a env['SERVER_PORT'] = str(self.server_port)
59n/a env['REMOTE_HOST']=''
60n/a env['CONTENT_LENGTH']=''
61n/a env['SCRIPT_NAME'] = ''
62n/a
63n/a def get_app(self):
64n/a return self.application
65n/a
66n/a def set_app(self,application):
67n/a self.application = application
68n/a
69n/a
70n/a
71n/aclass WSGIRequestHandler(BaseHTTPRequestHandler):
72n/a
73n/a server_version = "WSGIServer/" + __version__
74n/a
75n/a def get_environ(self):
76n/a env = self.server.base_environ.copy()
77n/a env['SERVER_PROTOCOL'] = self.request_version
78n/a env['SERVER_SOFTWARE'] = self.server_version
79n/a env['REQUEST_METHOD'] = self.command
80n/a if '?' in self.path:
81n/a path,query = self.path.split('?',1)
82n/a else:
83n/a path,query = self.path,''
84n/a
85n/a env['PATH_INFO'] = urllib.parse.unquote(path, 'iso-8859-1')
86n/a env['QUERY_STRING'] = query
87n/a
88n/a host = self.address_string()
89n/a if host != self.client_address[0]:
90n/a env['REMOTE_HOST'] = host
91n/a env['REMOTE_ADDR'] = self.client_address[0]
92n/a
93n/a if self.headers.get('content-type') is None:
94n/a env['CONTENT_TYPE'] = self.headers.get_content_type()
95n/a else:
96n/a env['CONTENT_TYPE'] = self.headers['content-type']
97n/a
98n/a length = self.headers.get('content-length')
99n/a if length:
100n/a env['CONTENT_LENGTH'] = length
101n/a
102n/a for k, v in self.headers.items():
103n/a k=k.replace('-','_').upper(); v=v.strip()
104n/a if k in env:
105n/a continue # skip content length, type,etc.
106n/a if 'HTTP_'+k in env:
107n/a env['HTTP_'+k] += ','+v # comma-separate multiple headers
108n/a else:
109n/a env['HTTP_'+k] = v
110n/a return env
111n/a
112n/a def get_stderr(self):
113n/a return sys.stderr
114n/a
115n/a def handle(self):
116n/a """Handle a single HTTP request"""
117n/a
118n/a self.raw_requestline = self.rfile.readline(65537)
119n/a if len(self.raw_requestline) > 65536:
120n/a self.requestline = ''
121n/a self.request_version = ''
122n/a self.command = ''
123n/a self.send_error(414)
124n/a return
125n/a
126n/a if not self.parse_request(): # An error code has been sent, just exit
127n/a return
128n/a
129n/a handler = ServerHandler(
130n/a self.rfile, self.wfile, self.get_stderr(), self.get_environ()
131n/a )
132n/a handler.request_handler = self # backpointer for logging
133n/a handler.run(self.server.get_app())
134n/a
135n/a
136n/a
137n/adef demo_app(environ,start_response):
138n/a from io import StringIO
139n/a stdout = StringIO()
140n/a print("Hello world!", file=stdout)
141n/a print(file=stdout)
142n/a h = sorted(environ.items())
143n/a for k,v in h:
144n/a print(k,'=',repr(v), file=stdout)
145n/a start_response("200 OK", [('Content-Type','text/plain; charset=utf-8')])
146n/a return [stdout.getvalue().encode("utf-8")]
147n/a
148n/a
149n/adef make_server(
150n/a host, port, app, server_class=WSGIServer, handler_class=WSGIRequestHandler
151n/a):
152n/a """Create a new WSGI server listening on `host` and `port` for `app`"""
153n/a server = server_class((host, port), handler_class)
154n/a server.set_app(app)
155n/a return server
156n/a
157n/a
158n/aif __name__ == '__main__':
159n/a with make_server('', 8000, demo_app) as httpd:
160n/a sa = httpd.socket.getsockname()
161n/a print("Serving HTTP on", sa[0], "port", sa[1], "...")
162n/a import webbrowser
163n/a webbrowser.open('http://localhost:8000/xyz?abc')
164n/a httpd.handle_request() # serve one request, then exit