-
Notifications
You must be signed in to change notification settings - Fork 0
/
nanoweb.py
176 lines (145 loc) · 5.8 KB
/
nanoweb.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
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
import uasyncio as asyncio
import uerrno
class HttpError(Exception):
pass
class Request:
url = ""
method = ""
headers = {}
route = ""
read = None
write = None
close = None
async def write(request, data):
await request.write(
data.encode('ISO-8859-1') if type(data) == str else data
)
async def error(request, code, reason):
await request.write("HTTP/1.1 %s %s\r\n\r\n" % (code, reason))
await request.write("<h1>%s</h1>" % (reason))
async def send_file(request, filename):
try:
with open(filename, "r") as f:
while True:
data = f.read(64)
if not data:
break
await request.write(data)
except OSError as e:
if e.args[0] != uerrno.ENOENT:
raise
raise HttpError(request, 404, "File Not Found")
class Nanoweb:
extract_headers = ('Authorization', 'Content-Length', 'Content-Type')
headers = {}
routes = {}
assets_extensions = ('html', 'css', 'js')
callback_request = None
callback_error = staticmethod(error)
INDEX_FILE = 'index.html'
def __init__(self, port=80, address='0.0.0.0'):
self.port = port
self.address = address
def route(self, route):
"""Route decorator"""
def decorator(func):
self.routes[route] = func
return func
return decorator
async def generate_output(self, request, handler):
"""Generate output from handler
`handler` can be :
* dict representing the template context
* string, considered as a path to a file
* tuple where the first item is filename and the second
is the template context
* callable, the output of which is sent to the client
"""
while True:
if isinstance(handler, dict):
handler = (request.url, handler)
if isinstance(handler, str):
await write(request, "HTTP/1.1 200 OK\r\n\r\n")
await send_file(request, handler)
elif isinstance(handler, tuple):
await write(request, "HTTP/1.1 200 OK\r\n\r\n")
filename, context = handler
context = context() if callable(context) else context
try:
with open(filename, "r") as f:
for l in f:
await write(request, l.format(**context))
except OSError as e:
if e.args[0] != uerrno.ENOENT:
raise
raise HttpError(request, 404, "File Not Found")
else:
handler = await handler(request)
if handler:
# handler can returns data that can be fed back
# to the input of the function
continue
break
async def handle(self, reader, writer):
items = await reader.readline()
items = items.decode('ascii').split()
if len(items) != 3:
return
request = Request()
request.read = reader.read
request.write = writer.awrite
request.close = writer.aclose
request.method, request.url, version = items
try:
try:
if version not in ("HTTP/1.0", "HTTP/1.1"):
raise HttpError(request, 505, "Version Not Supported")
while True:
items = await reader.readline()
items = items.decode('ascii').split(":", 1)
if len(items) == 2:
header, value = items
value = value.strip()
if header in self.extract_headers:
request.headers[header] = value
elif len(items) == 1:
break
if self.callback_request:
self.callback_request(request)
if request.url in self.routes:
# 1. If current url exists in routes
request.route = request.url
await self.generate_output(request,
self.routes[request.url])
else:
# 2. Search url in routes with wildcard
for route, handler in self.routes.items():
if route == request.url \
or (route[-1] == '*' and
request.url.startswith(route[:-1])):
request.route = route
await self.generate_output(request, handler)
break
else:
# 3. Try to load index file
if request.url in ('', '/'):
await send_file(request, self.INDEX_FILE)
else:
# 4. Current url have an assets extension ?
for extension in self.assets_extensions:
if request.url.endswith('.' + extension):
await send_file(request, request.url)
break
else:
raise HttpError(request, 404, "File Not Found")
except HttpError as e:
request, code, message = e.args
await self.callback_error(request, code, message)
except OSError as e:
# Skip ECONNRESET error (client abort request)
if e.args[0] != uerrno.ECONNRESET:
raise
finally:
await writer.aclose()
async def run(self):
await asyncio.start_server(self.handle, self.address, self.port)