顯示具有 python 標籤的文章。 顯示所有文章
顯示具有 python 標籤的文章。 顯示所有文章

2013/04/23

WebSocket on Tornado

Tornado 一直是我愛用的 python web framework,這幾年工作上一直在寫 event-drivent socket programming,所以被它 non-blocking 的特性給深深吸引,如果每件 block 的工作都能用 asynchronous 的方式來解決,那程式執行的效率一定超好!


延續『WebSocket 雙向即時通訊 - 初探』,今天就以 Tornado 來寫個簡單的 WebSocket 範例。當 client 連到 server 後,會傳送 hello ,而 server 回應一樣的訊息,傳送到第五次,server 就把 client 斷掉。

Server (ws_server.py)
import tornado.ioloop
import tornado.web
from tornado import websocket


class WSHandler(websocket.WebSocketHandler):
    count = 0
    def open(self):
        print "Client connected"

    def on_message(self, msg):
        print "[%d] Got message [%s] from client" % (self.count, msg)
        if self.count == 4:
            self.close()
            return
        # Write back message
        self.write_message("[%d] Echo: %s" % (self.count, msg))
        self.count += 1

    def on_close(self):
        print "Client disconnected"


application = tornado.web.Application([
    (r"/", WSHandler),
])

if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()



Client (ws_client.py)
from tornado.websocket import websocket_connect
from tornado.ioloop import IOLoop


class ws_client():
    conn = None # This is WebSocketClientConnection
    def __init__(self):
        websocket_connect('ws://localhost:8888/', callback=self.conn_cb)
        
    def conn_cb(self, future):
        self.conn = future.result()
        self.conn.write_message("hello")
        self.conn.read_message(self.read_cb)
        
    def read_cb(self, future):
        msg = future.result()
        if msg is None:
            print "Server disconnected"
            IOLoop.instance().stop()
        else:
            print msg
            self.conn.write_message("hello")
            self.conn.read_message(self.read_cb)

if __name__ == '__main__':
    ws_client()
    IOLoop.instance().start()

2013/03/24

在 Mac OS X 建置 python 開發環境

Install gcc for command line

Open XCode, click menu Preferences -> Downloads
check Command-Line Tools


Install Python-2.7.3

$ tar zxvf Python-2.7.3.tgz
$ cd Python-2.7.3
$ ./configure --prefix=/opt/Python-2.7.3
$ make && make install
$ export PATH=/opt/Python-2.7.3/bin:$PATH


Install distribute-0.6.35

$ tar zxvf distribute-0.6.27.tar.gz
$ cd distribute-0.6.27
$ python setup.py build
$ python setup.py install


Install pip-1.3.1

$ tar zxvf pip-1.1.tar.gz
$ cd pip-1.1
$ python setup.py build
$ python setup.py install


Install virtual environment

$ pip install virtualenv
$ virtualenv --no-site-packages /opt/pyenv
$ export PATH=/opt/pyenv/bin:$PATH



Install eclipse IDE

Download Eclipse Classic 4.2.2

Install PyDev plug-in for eclipse

Click menu Help -> Install New Software
Add repository with location: http://pydev.org/updates, then check the PyDev


Configure the interpreter

Click menu Preferences -> PyDev -> Interpreter - Python
Add new...
 

Add a new project and run it.
The debug mode is powerful.

2012/06/20

Python 基本開發環境建置

紀錄 python 開發環境的建置過程:

1. 安装 Python-2.7.2
$ tar zxvf Python-2.7.2.tgz
$ cd Python-2.7.2
$ ./configure && make && make install

2. 安装 distribute 0.6.27
$ tar zxvf distribute-0.6.27.tar.gz
$ cd distribute-0.6.27
$ python setup.py build
$ python setup.py install

3. 安裝 pip-1.1
$ tar zxvf pip-1.1.tar.gz
$ cd pip-1.1
$ python setup.py build
$ python setup.py install

4. 安裝 virtualenv 並建制 virtual environment
$ pip install virtualenv
$ virtualenv /opt/env

5. 指定 virtual environment 為預設開發環境
$ source /opt/env/bin/activate
可以看到command line提示改變 (pyenv)brian@localhost:~$
之後用 pip 安裝套件就會放在 /opt/env/lib 之下。


建立獨立的 virtual environment 好處就是比較"乾淨",如果你的系統有多個使用者,大家都裝到系統預設目錄則容易搞混。虛擬環境也可以建立多個,若同時跑多個專案或想切換不同 library 版本也很方便。另一方面也可以釐清開發這個專案"最小需求 library"是哪些,將來要 deploy 時也會比較順利。

2012/06/11

MySQL 如何避免 SQL injection

遇到這個問題,大部分的人應該會說:用 ORM (Object-relational mapping) 呀!但我就沒有打算多學一套 >< 一方面也是不清楚它欄位的屬性、資料形態是否完全支援 mysql,加上我執行的 query 也蠻複雜的。

先前有找了幾套:
  • SQLAlchemy - 大家比較推薦的
  • Quick ORM - fully compatible with the newest SQLAlchemy

ORM 的好處是你只要設定一次 mapping,之後 select、update、insert 都很方便,但我實在是沒有必要為了一個 injection protect 就用了這麼強大的東西。


除了 ORM 以外...
Search 了一下發現 MySQLdb 本身就有支援以參數的方式來執行 query:
cursor.execute('SELECT * FROM `user` WHERE user=%s AND password=%s;', usr, pwd)
所有的參數都會根據其資料型態來取代 format string,特殊字元自然就會被跳脫了。

要注意的是 statement 內的引號 " 要去掉,format string 通通使用 %s,像下面兩個語法就會有問題:
cursor.execute('SELECT * FROM `user` WHERE username="%s";', username)
cursor.execute('SELECT * FROM `user` WHERE id=%d;', my_id)

另外,也不要把 format string 串起來才傳過去,這樣就會真的發生 SQL injection了:
cursor.execute('SELECT * FROM `user` WHERE user=%s AND password=%s;' % (usr, pwd))

至於其他的 database 可以找看看有沒有 prepared statement 可以使用。


參考資料

Python: 頑固的 variable length argument

這邊卡了很久,做個筆記...

可變長度的參數傳遞
def p(fmt, *arg):
    print fmt % arg

# 傳多個參數
s1 = "hello"
s2 = "world"
p("%s %s", s1, s2)

# 把 list 的 element 當作參數
l = ["Allen", "Billy", "Elmer"]
p("%s %s %s", *tuple(l))

# 混合模式
l = ["Allen", "Billy", "Elmer"]
s = "hello"
p("%s, %s %s %s", *((s, ) + tuple(l)))
Output:
hello world
Allen Billy Elmer
hello, Allen Billy Elmer

2012/05/29

Python 串列(List)、字典(Dict) 的排序

List
直接對list本身排序
>>> l = [3, 2, 5, 4, 1]
>>> l.sort()
>>> l
[1, 2, 3, 4, 5]
>>> l.sort(reverse=True)
>>> l
[5, 4, 3, 2, 1]

不動到原始順序
>>> l = [3, 5, 4]
>>> sorted(l)
[3, 4, 5]
>>> l
[3, 5, 4]
根據element的運算結果
>>> l = ["tom", "Michael", "jenny"]
>>> l.sort(key=str.lower)
>>> l
['jenny', 'Michael', 'tom']


Dictionary
Dict本身是無序的,所以只能在輸出時做排序
>>> d = {"b": 1, "a": 3, "c": 2}
>>> d
{'a': 3, 'c': 2, 'b': 1}
>>> sorted(d)
['a', 'b', 'c']
>>> for key in sorted(d):
...     "%s: %d" % (key, d[key])
... 
'a: 3'
'b: 1'
'c: 2'


Dict in List
List.sort() 內的 key 是排序的依據,可以是 element 的屬性或是 function 運算後的結果
By function
>>> l = [{"id": 3, "name": "john"}, {"id": 2, "name": "brandon"}, {"id": 1, "name": "susan"}]
>>> l
[{'id': 3, 'name': 'john'}, {'id': 2, 'name': 'brandon'}, {'id': 1, 'name': 'susan'}]
>>> def my_func(d):
...     return d['id']
... 
>>> l.sort(key=my_func) 
>>> l
[{'id': 1, 'name': 'susan'}, {'id': 2, 'name': 'brandon'}, {'id': 3, 'name': 'john'}]

簡寫,use in-line function
>>> l.sort(key=lambda d:d['id'])   
>>> l
[{'id': 1, 'name': 'susan'}, {'id': 2, 'name': 'brandon'}, {'id': 3, 'name': 'john'}]
>>> l.sort(key=lambda d:d['name'])
>>> l
[{'id': 2, 'name': 'brandon'}, {'id': 3, 'name': 'john'}, {'id': 1, 'name': 'susan'}]


參考資料
HowTo/Sorting - PythonInfo Wiki

2012/05/21

Form validation in python web development

表單驗證

User 要傳資料到 server 不外乎就是透過 HTML 表單搭配 HTTP method GET/POST,為了避免 user 輸入奇怪的資料造成 server 異常,通常我們都會去限定各欄位值域、資料形態、格式...這些東西,如果自己用一堆 if 去寫一定會寫到瘋掉,好在網路上已經有現成的 library 可以用。

表單驗證有可以分別在 client 端或跟 server 端去做:
  • Client 端驗證
    好處是可以減少 server loading,少了傳輸的 latency,反應速度也比較快,但這只能防君子不能防小人,client 端驗證是用 javascript,有心人只要把 script 修改一下就可以避過。
    Library 可以參考:10 Useful jQuery Form Validation Techniques and Tutorials
  • Server 端驗證
    無論 client 端有沒有做,server 端做檢查是必然的事情啦!這也是我今天想介紹的,在 python 上我只用過一套:WTForms,一用就上癮,不只可以做到驗證,表單也可以自動產生。
    如果你 web framework 是用 flask,已經有現成的 extension: Flask-WTF 可以用,我自己是用 tornado,必須要另外疊一個 wrapper,幸好已經有人幫忙寫好了: flying with tornado on appengine

2012/03/21

Google app engine (GAE) - Hello World

Step by step 紀錄我的學習過程:

1. 申請 Google app engine

2. 環境
  • Python 2.5.2 - MacOS X有內建

3. 了解 Google App 限制

4. 了解 Google App 提供的資源

5. 下載SDK Python 專用的 Google 應用服務引擎 SDK
我自己是用 mac 版的圖形介面,按滑鼠右鍵選擇 new,然後選擇自己的 project directory,再來點左上角的 Run,就可以透過 localhost 去預覽自己的 app:
6. IDE - Eclipse
下載 Google Plugin for Eclipse

話說安裝的時候一直遇到下面的錯誤,最後換了一個網路環境就可以了,應該是網路問題吧?
An error occurred while collecting items to be installed
session context was:(profile=epp.package.jee, phase=org.eclipse.equinox.internal.p2.engine.phases.Collect, operand=, action=).
HTTP Server 'Bad Gateway' : http://dl.google.com/eclipse/plugin/3.7/plugins/com.google.gdt.eclipse.gph.subversive_2.5.2.v201202290255-rel-r37.jar
HttpClient connection error response code 502.


7. 範例 - Hello, World!
下載後,記得修改 app.yaml,application name 要填自己的才有辦法 deploy 到 server
application: ysl-test1
version: 1
runtime: python
api_version: 1

handlers:
- url: /.*
  script: helloworld.py


8. 部署 - 使用 appcfg.py
我自己是使用OS X的圖形介面,按一下右上角的 Deploy 就自動部署上到 google 了,部署成功訊息如下:

9. 瀏覽 http://(application_name).appspot.com 看看 Hello World有沒有 show 出來

10. 後台管理
  • 系統監控
  • 檢視 Log
  • Application 設定


小結
Google app engine架設網站相當快速、非常適合懶得自己架 server (IDC or AWS) 的人使用,所有的 application setting 透過 Web UI 就可以達成。
但跟 google 綁這麼緊密,使用它的data storage、API、管理工具、Log... 將來如果想轉到其他環境...應該會很難。



參考資料

2012/03/20

Build OpenCV error

我在編譯 OpenCV-2.3.1 for python 時遇到下面的錯誤

錯誤一:Linking error
$ cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D BUILD_PYTHON_SUPPORT=ON -D  PYTHON_INCLUDE_DIR=/usr/local/include/python2.6 -D PYTHON_LIBRARY=/usr/local/lib/libpython2.6.a ..
...
/usr/bin/ld: /usr/local/lib/libpython2.7.a(abstract.o): relocation R_X86_64_32 against `a local symbol' can not be used when making a shared object; recompile with -fPIC
/usr/local/lib/libpython2.7.a: could not read symbols: Bad value
collect2: ld returned 1 exit status
make[2]: *** [lib/cv2.so] Error 1
make[1]: *** [modules/python/CMakeFiles/opencv_python.dir/all] Error 2
make: *** [all] Error 2

解決方法就是重新編譯 python 加上 --enable-shared 的參數...找了好久lol
$ ./configure --enable-shared && make && make install


錯誤二:在 python 內找不到 cv module
Python 2.6.7 (r267:88850, Mar 20 2012, 11:54:21) 
[GCC 4.1.2 20080704 (Red Hat 4.1.2-52)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv
Traceback (most recent call last):
  File "stdin", line 1, in module
ImportError: No module named cv
>>>
/module/stdin

從 InstallGuide 得知解決方法:
1. 把cv.so和cv2.so copy到
2. 增加path到PYTHONPATH
export PYTHONPATH=~/projects/opencv/release/lib:$PYTHONPATH

2012/02/29

Tornado web framework + HTTPS

從官網得知 Tornado web framework 原本就有支援SSL協定
HTTPServer can serve SSL traffic with Python 2.6+ and OpenSSL. To make this server serve SSL traffic, send the ssl_options dictionary argument with the arguments required for the ssl.wrap_socket method, including “certfile” and “keyfile”:
    HTTPServer(applicaton, ssl_options={
        "certfile": os.path.join(data_dir, "mydomain.crt"),
        "keyfile": os.path.join(data_dir, "mydomain.key"),
    })

SSL Sample
import os
from tornado.httpserver import HTTPServer
from tornado.web import Application, RequestHandler
from tornado.ioloop import IOLoop

class MainHandler(RequestHandler):
    def get(self):
        self.write("Hello world!")

def main():
    application = Application([
        (r"/", MainHandler), 
    ])  

    http_server = HTTPServer(application,  
        ssl_options={
            "certfile": os.path.join(os.path.abspath("."), "test.crt"), 
            "keyfile": os.path.join(os.path.abspath("."), "test.key"), 
        }   
    )

    http_server.listen(8080)
    IOLoop.instance().start()

if __name__ == "__main__":
    main()

過程中需要ssl certificate 與 private key,可以用openssl產生,不過過程很繁雜,建議可以利用online tool:Create self-signed SSL certificates online

測試
開啓 http://localhost:8080 遇到錯誤:
ERROR:root:Exception in I/O handler for fd 3 Traceback (most recent call last): File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/tornado-2.0-py2.6.egg/tornado/ioloop.py", line 287, in start self._handlers[fd](fd, events) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/tornado-2.0-py2.6.egg/tornado/stack_context.py", line 159, in wrapped callback(*args, **kwargs) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/tornado-2.0-py2.6.egg/tornado/httpserver.py", line 294, in _handle_events except ssl.SSLError, err: AttributeError: 'module' object has no attribute 'SSLError' 

少了甚麼module嗎?
重裝openssl 0.9.8t -> 不行


安裝ssl package
# pip install ssl
ValueError: This extension should not be used with Python 2.6 or later (already built in), and has not been tested with Python 2.3.4 or earlier.
python 2.6以後的版本已經內建了


安裝pyopenssl package
# pip install pyopenssl
安裝成功,但結果還是一樣。看起來該有的都有了阿!


最後把deploy系統從mac os換到centos 5,一模一樣的步驟就...成功了!上面的問題至今未解...


如果看到這個warning,表示client的request是用http不是https,並不是server的問題唷!
WARNING:root:SSL Error on 7: [Errno 1] _ssl.c:490: error:1407609C:SSL routines:SSL23_GET_CLIENT_HELLO:http request

2011/09/21

Python Decorator (裝飾)

參考資料

Example 1
在原始function的return值做裝飾
def D1(fn):
    def newFn():
        return "" + fn() + ""
    return newFn

@D1
def f1():
    return "a sentence"

print f1()


2011/09/19

初學 Tornado web framework

最近需要架設一個線上平台,對於架設平台我實在沒什麼經驗,從前有開發過網站,會用asp.net、php自己刻東西,但時代不一樣了,為了講求快速,依附在framework上是有必要的。Tornado — 對我來說是個全新的開始,我不會python,對物件導向的程式語言也不熟,平常都在寫C語言居多,更別提用過web framework了...但我堅信我的底子跟熱情可以支撐我去學習這一切!

話說剛開始學習真的超不順,中文英文的教學都很少,官方的文件又寫的很簡略...但看著看著,突然有一天感覺就來了,就像任督二脈被打通般的,我看得懂了,我會使用了,程式寫這麼久了,我覺得對我幫助最大就是學會這種感覺。如果看懂Overview又學會使用Source code裡面的demo程式,對Tornado的掌握度就很高了!

API
Tornado真是個強大的東西,它陳列的API不多,但每一個都是在建立平台時很常見的需求:
  • OAuth第三方認證 - 使用facebook、google、twitter帳號來登入自己的網站,API都很精簡了
  • Python decorator tornado.web.authenticated - Sorry我不知道怎麼翻譯這個,簡單來說就是user尚未通過認證,存取到任何網頁都會被導回login頁面
  • Non-blocking, asynchronous http request - facebook graph API query、backend server query
  • Template - MVC架構開發,這是每個framewrok都必備的
  • Security cookie - 防止cookie被篡改
  • L10N, CSRF protect

IDE選擇

2011/09/14

Python 教學網站

基本語法教學 - 初學者用

推薦IDE - PyDev

如何在MacOS下安裝python套件?
參考官方網站 Python on the Macintosh

建議使用 Macports 套件管理程式來安裝:
# 搜尋套件
port list | grep python

# 安裝python主程式
sudo port install python26

# 安裝 easy_install
sudo port install py26-setuptools

#之後就可以利用easy_install去安裝更多python套件了

2011/07/21

Django初體驗

Web開發技術真是越來越強大了,一段時間沒碰就跟不上了,此時我的技術力還停留在ASP.Net 2.0與純PHP的時代... 快速開發與MVC架構似乎是framework的最大訴求,最近碰到要寫網頁,在想要選擇什麼走什麼路好,雖然有些許PHP底子,但最後是擔心PHP framework performance的問題,選擇了Python Django,開啟新的學習旅程~

第一步:Quick Start 照著做一次

第二步:了解MTV概念與專案內的manage.py settings.py urls.py各是做什麼用的

第三步:



Oh no! 遇到一些麻煩...
django-nonrel是用來補足Django NoSQL這一塊,目前支援的NoSQL有 MongoDB, ElasticSearch, Cassandra,但Amazon SimpleDB還沒完成阿!只好被迫放棄. (雖然說有找到 boto - Python interface to Amazon Web Services 提供了SimpleDB的存取方式,但就用不到ORM的特性了)


沒想到初體驗這麼快就結束了...