2013年6月7日 星期五

2013年6月6日 星期四

Python switch case

PHP :
switch(lang)
{
    case 'zh':
        zhDo(argu);
        break;
    case 'jp':
        jpDo(argu);
        break;
    default:
        enDo(argu);
        break;
}


Python :
try:
    {  
        'zh': zhDo,
        'jp': jpDo,
    }[lang](argu)
except KeyError:
    # default action
    enDo





Reference :
Python的switch…case语法 | vifix.cn

2013年6月4日 星期二

Python Bottle 操作 MySQL 的幾種方式

1. bottle_mysql plugin

需寫 SQL 語句

需透過 bottle route 傳入 db 連結句柄,靈活度不高

bottle-mysql 0.1.1 : Python Package Index

app = default_app()

db_plugin = mysql.Plugin(dbhost=DB_HOST, dbuser=DB_USER, dbpass=DB_PASS, dbname=DB_NAME, keyword='db')  # default keyword is db

app.install(db_plugin)


2. 自己封裝 MySQLdb 類別

需寫 SQL 語句

function 可重用

bottle-linkshorter/linkshorter.py at master · denschub/bottle-linkshorter · GitHub


3.使用 ORM

需要定義每個表格、欄位資訊

功能較強大 (基本功能不需寫 SQL 語句、資料欄位驗証、安全過濾)

CURD.py | Tiny Python ORM for MySQL — CURD.py | Tiny Python ORM for MySQL

SQLAlchemy - The Database Toolkit for Python (powerful)






Reference :
What are some good Python ORM solutions? - Stack Overflow