现在的位置: 首页 > 综合 > 正文

learn python the hard way 如何理解web 服务器的响应机制

2013年08月30日 ⁄ 综合 ⁄ 共 1125字 ⁄ 字号 评论关闭

在学习python时对web服务器响应机制有一些理解,为防以后忘记,在此记录一下:

bin/app.py


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import web

urls = (
  '/hello', 'Index'
)

app = web.application(urls, globals())

render = web.template.render('templates/')

class Index(object):
    def GET(self):
        return render.hello_form()

    def POST(self):
        form = web.input(name="Nobody", greet="Hello")
        greeting = "%s, %s" % (form.greet, form.name)
        return render.index(greeting = greeting)

if __name__ == "__main__":
    app.run()

 templates/hello_form.html

<html>
    <head>
        <title>Sample Web Form</title>
    </head>
<body>

<h1>Fill Out This Form</h1>

<form action="/hello" method="POST">
    A Greeting: <input type="text" name="greet">
    <br/>
    Your Name: <input type="text" name="name">
    <br/>
    <input type="submit">
</form>

</body>
</html>

templates/index.html :

$def with (greeting)

<html>
    <head>
        <title>Gothons Of Planet Percal #25</title>
    </head>
<body>

$if greeting:
    I just wanted to say <em style="color: green; font-size: 2em;">$greeting</em>.
$else:
    <em>Hello</em>, world!

</body>
</html>

首先 在浏览器地址栏输入  http://localhost:8080/hello

开始响应app.py中的GET函数,GET函数返回hello_form()也就是templates 下的hello_form.html表单
之后hello_form表单用POST方法将"/hello"这个url再次抛给浏览器,那么浏览器再次找到"/hello"的class index这个类,找到
POST方法,由POST方法 响应templates下的index  输出  

抱歉!评论已关闭.