blog.Ring.idv.tw

Python

Python Server Pages - SQLite3

由於自從Python 2.5推出之後,它就內含了「SQLite (lightweight disk-based database)」,它是一個C library~ 所以有相當多的平台都將它當作內部的儲存方式,好比如:Google Android、Adobe AIR、Google Gears..

所以這篇主要記錄一些簡單的操作~ 感覺有點像一般小型ASP+Access網站的架構模式~

範例如下:

db.py

from mod_python import apache, psp
import sqlite3

def index(req):
	req.content_type = 'text/html'
	conn = sqlite3.connect('data.dat')
	c = conn.cursor()

	c.execute('''
	create table members(
		id int,
		name varchar,
		login timestamp
	)
	''')
	 
	c.execute('''
	insert into members
	values (1,'jeff','2006-10-01')
	''')
	c.execute('''
	insert into members
	values (2,'angie','2006-10-02')
	''')
	c.execute('''
	insert into members
	values (3,'dylan','2006-10-03')
	''')
	
	conn.commit()
	c.execute('select * from members')
	res = c.fetchall()

	who = "jeff"
	c.execute("select id,name,login from members where name=:who", {"who": who})
	jeff = c.fetchone()

	template = psp.PSP(req, filename='db.tmpl')
	template.run({'results':res,'jeff':jeff})

db.tmpl

<html>
<p><%=jeff%></p>
<%
for f in results:
%>
<%=f[0]%><%=f[1]%><%=f[2]%><br/>
<%
%>
</html>

相關資源

sqlite3 -- DB-API 2.0 interface for SQLite databases

2008-10-01 02:36:50 | Add Comment

Python Server Pages - Nested PSP Templates

在上一篇「Python Server Pages - Forms」已經簡單的記錄一下「Form」的處理~

而這篇則是針對如果我們想在同一份頁面中~ 分離多個「Template」來進行處理~ 它就稱作「Nested PSP Templates」。

我們仍然以上一篇文章的例子來作解釋以方便理解。

Nested PSP Templates

「form.html」不需要變動到它,只要更動「index.py」和相關的「templates」即可。

index.py

from mod_python import apache, psp

def index(req,userid,fruit):
	req.content_type = 'text/html'
	uid_temp = psp.PSP(req, filename='uid.tmpl',vars = {'uid':userid})
	fruit_temp = psp.PSP(req, filename='fruit.tmpl')
	fruit_temp.run({'fruit':fruit,'uid_temp':uid_temp})

從這個例子可以發現,我們同時使用到「uid.tmpl」和「fruit.tmpl」來處理同一份頁面。

uid.tmpl

<h1>Hello, <%=uid%></h1>

fruit.tmpl

<html>
<%=uid_temp%>
<%
for f in fruit:
%>
<%=f%>
<%
%>
</html>

在這個範例上,整個重點就在於「uid_temp」已經優先被剖析和編譯了,直到執行「fruit_temp.run()」時才會整個傳送到Client端~

相關資源

4.9 psp - Python Server Pages

2008-10-01 01:43:01 | Add Comment

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 | Add Comment

Universal Encoding Detector - 編碼偵測(Python)

什麼時候我們需要做「編碼偵測」的動作呢?最明顯的例子不外乎就是「瀏覽器」~ 假設我們的網頁沒附上「<meta http-equiv="Content-Type" content="text/html;charset=utf-8">」這樣的字句~ 那Browser還能有足夠的能力偵測此網頁是用何種編碼的嗎?

再舉另一個例子~ 當我們寫了一個Crawler來爬行網頁的同時~ 在下載這些網頁之後~ 我們又該如何得知這些網頁的編碼呢?

所以~ 「編碼偵測」算是處理文字資訊前的必要動作~ 而「Universal Encoding Detector」就提供了一個這麼好的工具~ 當然也是給它Open Source的嚕~ 不過這是針對Python語言的~ 當然也還有其它的解決方案~ 就請參考相關資源!

Universal Encoding Detector

Universal Encoding Detector」目前的版本是1.0.1版~ 而在使用它之前必須先安裝在你的電腦~

下載:chardet-1.0.1.tgz

安裝過程如下:

tar zxvf chardet-1.0.1.tgz
cd chardet-1.0.1
setup.py build
setup.py install

接著就給它寫一個簡單的測試程式:

import urllib2, chardet

if __name__ == "__main__":
	urlread = lambda url: urllib2.urlopen(url).read()
	running = True
	while running:
		str = raw_input('Please enter a url: ')
		if str == 'q':
			running = False
		else:
			print chardet.detect(urlread(str))
	else:
		print 'Done'

測試結果:

Please enter a url: http://www.google.com.cn
{'confidence': 0.98999999999999999, 'encoding': 'GB2312'}
Please enter a url: http://blog.ring.idv.tw
{'confidence': 0.98999999999999999, 'encoding': 'utf-8'}
Please enter a url: http://www.cnn.com
{'confidence': 1.0, 'encoding': 'ascii'}
Please enter a url: q
Done

相關資源

中文編碼偵測 || William's Blog

A composite approach to language/encoding detection

大步向前走: Programming 自動偵測編碼

Shared Development: Character encoding detection

Java port of Mozilla charset detector

cpdetector, free java code page detection.

2008-09-29 03:11:15 | Add Comment

Python Server Pages - 架構一個PSP環境

在Web Application的開發工具中,絕大多數耳熟能詳的Server Side Programming無非就是ASP、PHP和JSP,那... Python呢?

我們是否也能使用Python來開發Web Application呢?答案是肯定的~

通常在架設LAMP(PHP)環境時~ 在安裝好Apache之後,就是要為它加上「mod_php」這個module,這樣Apache才能委任由此module來處理PHP~

OK,換句話說~ 若是要讓Apache和Python緊密地結合在一起~ 這時候我們需要的就是「mod_python」...

至於Web Framework的選擇方案... 在Java領域中不外乎有StrutsSpring,PHP也有Zend FrameworkCakePHP~ 那Python哩?也有DjangoTurboGears~ 不過我沒用過倒是真的~ XDD

所以本文就是要建構一個「Apache」結合「Python」等於「Python Server Pages(PSP)」的環境~

環境配置

.作業環境Windows XP Home Edition

.Apache 2.2

.Python 2.5

.mod_python(請下載並安裝:mod_python-3.3.1.win32-py2.5-Apache2.2.exe)

httpd.conf設定

安裝「mod_python」之後,在「Apache」的modules目錄夾之中會產生一個「mod_python.so」~ 所以我們需要修改「httpd.conf」將這個module載入進來~

.加入此行「LoadModule python_module modules/mod_python.so」

.尋找「<Directory "/some/directory/htdocs">」(/some/directory/指的是你Apache所安裝的位置),並改寫「AllowOverride」屬性為「FileInfo」,如:

AllowOverride FileInfo

HelloWorld範例 (Template System)

現在在「htdocs」目錄下建立一個「psp」的目錄夾,並寫入下述三份文件:

.htaccess

SetHandler mod_python
PythonHandler mod_python.publisher
PythonDebug On

hello.py

from mod_python import apache, psp
def handler(req):
	req.content_type = 'text/html'
	template = psp.PSP(req, filename='hello.tmpl')
	template.run({'what':'world'})

hello.tmpl

<html>
	<h1>Hello, <%=what%>!</h1>
</html>

測試它吧!

最後的步驟就是開啟你的Browser,在網址列上給它填上「http://localhost/psp/hello/handler」你就能看見「Hello, world!」~ ^^v

相關資源

modpython官網

Mod_python's PSP: Python Server Pages

Web Python Tutorial

2008-08-06 15:58:00 | Comments (2)

Next Posts~:::~Previous Posts
Copyright (C) Ching-Shen Chen. All rights reserved.

::: 搜尋 :::

::: 分類 :::

::: Ads :::

::: 最新文章 :::

::: 最新回應 :::

::: 訂閱 :::

Atom feed
Atom Comment