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

2014年4月24日 星期四

Flask Note 1

想要來寫個Flask筆記, 這個系列會把一些看到, 或是曾經使用過的技術給記錄下來

環境需求:python2.7以上, python套件pip & virtualenv安裝

0. 建立virtualenv環境, 使用virturlenv目的就是為了建立一個乾淨的開發環境, 可以去掌握你撰寫的python程式跟其他package的相依性, 利於你的程式部署到其他機器上
$ pip install virtualenv
Requirement already satisfied (use --upgrade to upgrade): virtualenv in /Library/Python/2.7/site-packages
Cleaning up...
$ virtualenv .env
New python executable in .env/bin/python
Installing Setuptools..............................................................................................................................................................................................................................done.
Installing Pip.....................................................................................................................................................................................................................................................................................................................................done.
$ source .env/bin/activate #進入virtualenv環境
(.env) $
1. 在virtual environment 下安裝 Flask
$ virtualenv .env
(.env) $ pip install flask
2. 產生app instance
from flask import Flask
app = Flask(__name__)
3. 建立Route
from flask import Flask
app = Flask(__name__) 

@app.route('/')
def index():
    return 'Hello World !!!'

@app.route('/user/<name>/')
def user(name):
    return 'hello %s' % name

if __name__ == '__main__':
    app.run(debug=True);
4. run script by python interpreter
$(.env) python hello.py
*Running on http://127.0.0.1:5000/
*Restarting with reloader
接下來可以打開瀏覽器輸入http://127.0.0.1:5000/看看
還有http://127.0.0.1:5000/user/test
       http://127.0.0.1:5000/user/world

2010年11月27日 星期六

python

kakashi@kakashi-laptop:~$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

2009年11月17日 星期二

python object and static method

這是一則早該紀錄的文章,只能說我太懶惰了-.-,一切都是從這裡開始的,有天心血來潮想來review一下design pattern,結果跑去看良葛格的文章simple factory ,可是問題跑出來了,他下面的python code我不能跑,會出現錯誤跑出

TypeError: unbound method getMessage() must be called with MessageFactory instance as first argument (got str instance instead)

因為MessageFactory.getMessage("caterpillar@openhome.cc", "Hi")這行程式碼的MessageFactory沒有初始化出來,這和我們預期要的結果不同,我們原本就是要用工廠來封裝製作物件的過程,所以我們並不需要將messageFactory 的 instance建立出來,後來找到了class method differences in python : bound, unbound , and static文章,原來只要將def getMessage(addr, msg):上面加上@staticmethod decorator就不會有錯誤了!

另外也讓我了解到python的物件特性
Class Test(Object):
  def method_one(self):
    print "Called method_one"

  def method_two():
    print "Called method_two"

a_test = Test()
a_test.method_one()
a_test.method_two()
一個bound function 會被翻譯成為

a_test.method_one()  --->  Test.method_one(a_test)

所以使用method_two就會寫少一個argument
>>> a_test = Test()
>>> a_test.method_two()
Traceback (most recent call last): 
  File " ", line 1, in 
TypeError: method_two() takes no arguments (1 given)
如果你要改變這種情形 可以用decorator
class Test(object):
    def method_one(self):
        print "Called method_one"

    @staticmethod
    def method_two():
        print "Called method two"

2009年9月8日 星期二

FreeBSD + Apache2 + Mod_wsgi + Django

最近在搞django , 之前試過在lighttpd上面用fastcgi跑django,不過光安裝就讓我一個頭兩個大,這次在不考慮效能的情況下想試試看用apache2 + mod_wsgi + django的安裝模式, 看是否有比較快, 安裝過程參考http://www.indexofire.com/blog/?p=243

幾乎是一模一樣啦,不過最後的地方我有特別標示清楚

1. FreeBSD是7.2,先更新完ports
2. Ports安装Apache2.2
#cd /usr/ports/www/apache22/
#make install clean
3. Ports安裝python2.6 (FreeBSD 預設沒有安裝python還讓我蠻吃驚的)
#cd /usr/ports/lang/python26/
#make install clean
4. Ports安裝mod_wsgi
#cd /usr/ports/www/mod_wsgi
#make install clean
5. Ports安装Django1.1
#cd /usr/ports/www/py-django
#make install clean
裝完他會提供你可以裝的database
我想試試看sqlite3
6. Ports安裝sqlite3
#cd /usr/ports/databases/py-sqlite3
#make install clean
7. 設定http.conf
在家目錄裡面建立一個django的資料夾當作我們的目錄
#mkdir -p /usr/local/www/apache22/django
#cd /usr/local/www/apache22/django
#django-admin.py startproject cms
增加httpd.conf以下內容
WSGIScriptAlias /cms /usr/local/www/apache22/django/cms/django.wsgi

WSGIApplicationGroup %{GLOBAL}
Order deny,allow
Allow from all

8. 接著建構django.wsgi
import os, sys

sys.path.append('/usr/local/www/apache22/django')
os.environ['DJANGO_SETTINGS_MODULE'] = 'cms.settings'

import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
9. 看一下http://localhost/cms是否成功!~

2009年7月15日 星期三

python UnicodeEncodeError

最近在玩qPlurk遇到的一個問題 UnicodeEncodeError: 'ascii' codec can't encode characters in position 42-44: ordinal not in range(128) 好像是因為再拿html的時候出的問題 解決的辦法就是利用 import sys reload(sys) sys.setdefaultencoding("utf-8") reference: 從這個站看來的