-
Notifications
You must be signed in to change notification settings - Fork 1
/
framework.py
79 lines (62 loc) · 2.24 KB
/
framework.py
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
import wsgiref.headers
import re
from parse import parse
class NotFound(Exception):
pass
class Request:
def __init__(self, environ):
self.environ = environ
@property
def path(self):
return self.environ.get('PATH_INFO')
@property
def method(self):
return self.environ.get('REQUEST_METHOD')
class Response:
def __init__(self, response_body=None, status=200, charset='utf-8', content_type='text/html'):
self._status = status
self.charset = charset
self.content_type = content_type
self.response_body = response_body.encode('utf-8')
self.headers = wsgiref.headers.Headers()
self.headers.add_header('content-type', f'{content_type}; charset={charset})')
@property
def status(self):
from http.client import responses
status_string = responses.get(self._status, 'UNKNOWN STATUS')
return f'{self._status} {status_string}'
def __iter__(self):
yield self.response_body
def jsonify(data):
import json
return Response(json.dumps(data), content_type='application/json')
class App:
def __init__(self):
self.routing = []
def resolve_arguments(self, callback, request):
kwargs = {}
for name, _type in callback.__annotations__.items():
if _type is Request:
kwargs[name] = request
return kwargs
def route(self, pattern):
def wrapper(callback):
self.routing.append((pattern, callback))
return callback
return wrapper
def match(self, path):
for pattern, handler in self.routing:
parse_result = parse(pattern, path)
if parse_result is not None:
return handler, parse_result.named
raise NotFound()
def __call__(self, environ, start_response):
try:
request = Request(environ)
callback, kwargs = self.match(request.path)
_kwargs = self.resolve_arguments(callback, request)
response = callback(**kwargs, **_kwargs)
except NotFound:
response = Response('<h1>404 Not Found</h1>', status=404)
start_response(response.status, response.headers.items())
return response