blog.Ring.idv.tw

Python Server Pages - Forms

Python Server Pages - Forms


先前筆者有寫了一篇簡單的PSP(Python Server Pages)介紹「Python Server Pages - 架構一個PSP環境」,不過那篇是針對「Windows」環境下的設置~ 如果我們要在「Linux」的環境下Run的話~ 同樣地~ 安裝「libapache2-mod-python」即可。(請注意:Debian 4.0r4 預設是Python2.4,若你要安裝Python2.5請參考「Jason R Briggs · mod_python and python2.5」)

如下:

apt-get install libapache2-mod-python

且先前的「Hello World」範例就直接用「Templating System」來實作了~ 因為透過「templating mechanism」可以幫助我們將「Business Logic」和「Presentation」來做個分離~ 以後在維護上就會較方便,且容易除錯~

而這篇主要來記錄PSP是如何處理「Form」,就直接看下述範例:

Python Server Pages - Forms

如同先前所介紹的,這邊我們仍然以「psp」的目錄來測試。

.htaccess

SetHandler mod_python
PythonHandler mod_python.publisher
PythonDebug On

<Files ~ "\.(gif|html|jpg|png)$">
   SetHandler default-handler
</Files>

form.html

<html>
<body>
<form action="/psp/" method="post">
<p>UserID: <input type="text" name="userid">
<br/>
<input type="checkbox" name="fruit" value="apple">Apple
<input type="checkbox" name="fruit" value="banana">Banana
<input type="checkbox" name="fruit" value="grape">Grape
<input type="submit" value="Submit"></p>
</form>
</body>
</html>

index.py

from mod_python import apache, psp
from cgi import escape

def index(req):
	req.content_type = 'text/html'
	template = psp.PSP(req, filename='hello.tmpl')
	_fruit = req.form.getlist('fruit')
	_fruit = map(lambda fruit: escape(fruit), _fruit)
	_uid = req.form.getfirst('userid')
	_uid = escape(_uid)
	template.run({'uid':_uid,'fruit':_fruit})

hello.tmpl

<html>
	<h1>Hello, <%=uid%></h1>
<%
for f in fruit:
%>
<%=f%>
<%
%>
</html>

最後打開你的瀏覽器,輸入「http://localhost/psp/form.html」來測試~ 應該就沒啥問題了!

從這個例子我們可以知道說~ 要取得「Form」的資料必須透過「Request」這個物件裡面的「form」attribute來取得~

重點在於「form」attribute就是FieldStorage類別的instance,而它儲存了一份reference在「Request」物件中的「form」attribute

雖然我們可以透過「FieldStorage」來取得「Form」的資料~ 但其實還有更快的方式~

我們可以直接利用定義函式中所要傳入的參數來對應即可~ 如下所示:

def index(req,userid,fruit):
.....

只要參數名稱對應「Form」的欄位名稱即可。

2008-10-01 01:17:11

Leave a Comment

Copyright (C) Ching-Shen Chen. All rights reserved.

::: 搜尋 :::

::: 分類 :::

::: Ads :::

::: 最新文章 :::

::: 最新回應 :::

::: 訂閱 :::

Atom feed
Atom Comment