-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
executable file
·51 lines (37 loc) · 1.15 KB
/
main.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
from http.server import BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs
def fibonacci(n: int):
"""Return the first `n` Fibonacci numbers."""
if n <= 0:
return []
elif n == 1:
return [0]
elif n == 2:
return [0, 1]
fib_nums = [0, 1]
for i in range(2, n):
fib_nums.append(fib_nums[-1] + fib_nums[-2])
return fib_nums
class GetFibs(BaseHTTPRequestHandler):
def do_GET(self):
query = urlparse(self.path).query
params = parse_qs(query)
if "n" not in params:
self.send_response(422)
return
try:
key = int(params["n"][0])
except (IndexError, ValueError):
self.send_response(422)
nums = fibonacci(key)
# convert nums from int to string list
str_nums = [str(n) for n in nums]
final_nums = ", ".join(str_nums)
self.send_response(200)
self.end_headers()
self.wfile.write(bytes(final_nums, "UTF-8"))
return
if __name__ == "__main__":
from http.server import HTTPServer
httpd = HTTPServer(("", 8000), GetFibs)
httpd.serve_forever()