Repository navigation
Expand file tree
/
Copy pathserver.py
More file actions
93 lines (65 loc) · 2.07 KB
/
Copy pathserver.py
File metadata and controls
93 lines (65 loc) · 2.07 KB
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
from http.server import BaseHTTPRequestHandler, HTTPServer
import math
def check_if_prime(number):
if number % 2 == 0 and number != 2:
return False
for i in range(3, math.floor(math.sqrt(number)) + 1, 2):
if number % i == 0:
return False
return True
def prime_numbers_up_to(up_to):
primes = [number for number in range(1, up_to + 1)
if check_if_prime(number)]
return primes
def extract_param(path):
'''
Extract the parameter and transform into
a positive integer. If the parameter is
not valid, return None
'''
raw_param = path.replace('/', '')
# Try to convert in number
try:
param = int(raw_param)
except ValueError:
return None
# Check that it's positive
if param < 0:
return None
return param
def get_result(path):
param = extract_param(path)
if param is None:
return 'Invalid parameter, please add an integer'
return prime_numbers_up_to(param)
class MyServer(BaseHTTPRequestHandler):
def do_GET(self):
result = get_result(self.path)
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
return_template = '''
<html>
<head><title>Example</title></head>
<body>
<p>Add a positive integer number in the path to display
all primes up to that number</p>
<p>Result {result}</p>
</body>
</html>
'''
body = bytes(return_template.format(result=result), 'utf-8')
self.wfile.write(body)
if __name__ == '__main__':
HOST = 'localhost'
PORT = 8000
web_server = HTTPServer((HOST, PORT), MyServer)
print(f'Server available at http://{HOST}:{PORT}')
print('Use CTR+C to stop it')
# Capture gracefully the end of the server by KeyboardInterrupt
try:
web_server.serve_forever()
except KeyboardInterrupt:
pass
web_server.server_close()
print("Server stopped.")