-
-
Save kawamou/3496483e9f4852265186693ff0479900 to your computer and use it in GitHub Desktop.
Writing your own HTTP Server - Implementing WSGI: WSGI class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import sys | |
| from io import StringIO | |
| class WSGI: | |
| def __init__(self, config): | |
| import importlib.util | |
| self.config = config | |
| app_loc, app_module, app = config['app-loc'], config['app-module'], config['app'] | |
| spec = importlib.util.spec_from_file_location(app_module, app_loc + f"/{app_module}.py") | |
| module = importlib.util.module_from_spec(spec) | |
| spec.loader.exec_module(module) | |
| self.app = getattr(module, app) | |
| def process(self, parsed_request, write): | |
| body = [] | |
| if parsed_request.is_partial_body(): | |
| body.append(parsed_request.recv_body()) | |
| body = StringIO("".join(body)) | |
| env = { | |
| 'REQUEST_METHOD': parsed_request.get_method(), | |
| 'SCRIPT_NAME': '', | |
| 'PATH_INFO': parsed_request.get_path(), | |
| 'SERVER_NAME': self.config['address'], | |
| 'SERVER_PORT': self.config['port'], | |
| 'SERVER_PROTOCOL': 'HTTP/1.1', | |
| 'wsgi.version': (1, 0), | |
| 'wsgi.url_scheme': 'http', | |
| 'wsgi.input': body, | |
| 'wsgi.errors': sys.stderr, | |
| 'wsgi.multithread': True, | |
| 'wsgi.multiprocess': True, | |
| 'wsgi.run_once': False | |
| } | |
| for header, value in parsed_request.get_headers().items(): | |
| env[f'HTTP_{header}'] = value | |
| headers = [] | |
| def start_response(status, response_headers, exc_info=None): | |
| nonlocal headers | |
| headers = [status, response_headers] | |
| outputs = self.app(env, start_response) | |
| status, response_headers = headers | |
| write(str.encode('HTTP/1.1: %s\r\n' % status)) | |
| for header in response_headers: | |
| write(str.encode('%s: %s\r\n' % header)) | |
| write(str.encode('\r\n')) | |
| for output in outputs: | |
| write(output) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment