python web py入門-4-請求處理(上)
這篇我們來介紹一下請求處理過程。其實,在前面python中requests做接口自動化的系列講過請求和響應。服務器需要對客戶端發送的請求,進行解析和處理。我們在前面文章介紹的URL映射,每次輸入新的URL都是一次發送請求的過程。在cmd里可以看到這些請求的記錄。
1. 用客戶端合肥服務器的圖形表示如下
文字解釋下,一開始瀏覽器給服務器發送一個請求,請求數據主要由請求行,head,body組成。如果是post請求,requset line里面只有地址沒有參數,參數放在了body里面。如果是get請求,request line里面包括URL和接口參數拼接在后面。body就是空。同樣響應內容也有響應行,頭部,body三部分組成。
2.代碼實現請求處理
在web.py中請求參數獲取是用方法web.input(); 請求頭信息是用方法: web.ctx.env
我們做一個123.html的表單,方便待會測試POST請求
-
<html>
-
<head>
-
<title>hello 123</title>
-
</head>
-
<body>
-
<h1>POST</h1>
-
<form action="/blog/123" method="POST">
-
<input type="text" name="id" value=""/>
-
<input type="password" name="password" value=""/>
-
<input type="submit" value="submit">
-
</form>
-
</body>
-
-
</html>
然后我們修改下hello.py內容,主要是增加get和post方法獲取參數。hello.py和123.html兩個文件需要放在同一個目錄下,例如桌面。
-
import web
-
-
urls = (
-
'/index', 'index',
-
'/blog/\d+', 'blog',
-
'/(.*)', 'hello'
-
)
-
app = web.application(urls, globals())
-
-
class hello:
-
def GET(self, name):
-
return open(r'123.html').read()
-
-
class index:
-
def GET(self):
-
query = web.input()
-
return query
-
-
class blog:
-
def POST(self):
-
data = web.input()
-
return data
-
-
if __name__ == "__main__":
-
app.run()
2.測試效果
先來看看,瀏覽器訪問http://127.0.0.1:8080/index?name=Anthony&city=Beijing,然后回車。
可以看到,獲取到了get方法的參數。
再看看post請求參數獲取,我們瀏覽器輸入如下圖,輸入用戶名和密碼。
點擊提交之后,可以獲取到剛剛輸入的值。
通過上面的舉例,我們驗證了web.py GET和POST是如何獲取請求參數的。