-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
49 lines (35 loc) · 1.38 KB
/
server.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
from src.serve import App, Router
import os
names = []
def names_to_html():
names_str = ''
for name in names:
names_str += '\n<li>'
name = name.replace('<', '<')
name = name.replace('>', '>')
names_str += name
names_str += '</li>'
return names_str + '\n'
if __name__ == '__main__':
def listening():
print("App is listening at localhost on port 8080")
def log_incoming_request(req, res, next):
print('[%s] %s' % (req.method, req.originalUrl) ) # print the request type and path
next() # make sure the endware is reached
def serve_homepage(req, res):
homepage = open(os.path.join(os.path.dirname(__file__), 'home.html'), 'r').read() # read the file as a string
homepage = homepage.replace('{{names}}', names_to_html()) # replace {{names}} with a list
res.status(200).set('Content-Type', 'text/html').send( homepage ) # send it back as html
def post_name(req, res):
names.append(req.body['name']) # add the name to the list
serve_homepage(req, res) # serve the homepage the same
app = App()
router = Router()
# mount the endware
router.get('/', serve_homepage)
router.post('/', post_name)
# mount the middleware
app.use(router)
app.use(log_incoming_request)
# start the server
app.listen(port=8080, callback=listening)