1. 程式人生 > >20170901 基於wsgi的web框架二

20170901 基於wsgi的web框架二

err cursor cte rem word tab ons turn display

20170901 基於wsgi的web框架二

<wiz_code_mirror> 1
from wsgiref.simple_server import make_server
2
import time
3




4





5

def f1(environ):
6
    return [b"<h1>hello book</h1>"]
7



 
 

8





9

def f2(environ):
10
    return [b"<h1>web</h1>"]
11




12





13

def default(environ):
14
    return [b"<h1>hello world</h1>"]
15




16





17

def login(environ):
18
    return [b‘<h1>hello , login!</h>‘]
19




20





21

def current_time(environ):
22
    f = open("current_time.html", "rb")
23
    data = f.read()
24
    cur_time = time.ctime(time.time())
25
    data = str(data, "utf8").replace("!cur_time!", str(cur_time))
26
    return [data.encode("utf8")]
27




28





29

def routers():
30
    urlpatterns = {
31
        (‘/current_time‘, current_time),
32
        (‘/book‘, f1),
33
        (‘/web‘, f2),
34
        (‘/login‘, login),
35
    }
36
    return urlpatterns
37




38





39

def application(environ, start_response):
40
    start_response(‘200 OK‘, [(‘Content-Type‘, ‘text/html‘)])
41
    path = environ["PATH_INFO"]  # path==‘/book‘
42




43

    urlpatterns = routers()
44
    func = None
45
    for item in urlpatterns:
46
        if item[0] == path:
47
            func = item[1]
48
            break
49
    if func:
50
        return func(environ)
51




52





53

# 封裝了socket對象以及準備過程(bind, listen)
54
httpd = make_server(‘‘, 8080, application)
55




56

print(‘Serving HTTP on port 8080...‘)
57
# 開始監聽HTTP請求:
58
httpd.serve_forever()
59







 
 



<wiz_code_mirror>

 
 
 







10


 
 

 



 
 

1

<!DOCTYPE html>
2
<html lang="en">
3
<head>
4
    <meta charset="UTF-8">
5
    <title>Title</title>
6
</head>
7
<body>
8
<h1>current_time:!cur_time!</h1>
9
</body>
10
</html>

20170901 基於wsgi的web框架二