关于‘Python’

Python处理Last-Modified

发表于2011年11月16日

Python检查某个URI是否有修改,可以检查HTTP Response的Last-Modified字段

import urllib2
import datetime
from urllib2 import HTTPError
import datetime
def check_modified(url, last_modified, field_name="Last-Modified"):
    request = urllib2.Request(url) 
    opener = urllib2.build_opener() 
    request.add_header('If-Modified-Since', last_modified)
    try:
        resp = opener.open(request)
        print "Last-Modified: " + resp.headers.get(field_name)
    except HTTPError as e:
        if 304 == e.code:
            print "Not Modified Since: " + last_modified
 
last_modified = datetime.datetime(2011,11,15,0,0).strftime("%a, %d %h %Y %H:%M:%S GMT")
check_modified('http://www.kuaishubao.com', last_modified)

有的服务器并不返回Last-Modified, 所以需要看情况处理,比如

check_modified('http://sunliwen.com', last_modified, field_name="date")

参考:http://www.faqs.org/rfcs/rfc2616.html

用Python Decorator简化代码

发表于2011年10月14日

看码不说话。

def deco(callable):
    def method(a, b):
        print "a: %s" % a
        print "b: %s" % b
        return callable(a, b)
    return method
 
@deco
def test1(a,b):
    print a+b
 
test1(10,20)

上面的Decorator只能装饰有两个参数的函数,否则

@deco
def test2(a,b,c):
    print a+b+c

会报错

>>> test2(10,20,30)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: method() takes exactly 2 arguments (3 given)

如需支持装饰任意参数的函数,得使用以下方法:

def deco(callable):
    def method(*args, **kws):
        print "args: %s" % repr(args)
        print "kws: %s" % repr(kws)
        return callable(*args, **kws)
    return method
 
@deco
def test1(a,b):
    print a+b
 
@deco
def test2(a,b,c):
    print a+b+c
 
test1(10,20)
test1(10,b=20)
test2(10,20,30)
test2(10,b=20,c=30)

结果是:

>>> test1(10,20)
args: (10, 20)
args: {}
30
>>> test1(10,b=20)
args: (10,)
args: {'b': 20}
30
>>> test2(10,20,30)
args: (10, 20, 30)
args: {}
60
>>> test2(10,b=20,c=30)
args: (10,)
args: {'c': 30, 'b': 20}
60

Ubuntu下安装PHP-FPM

发表于2011年9月18日

把VPS的Lenny5换成了Ubuntu10.04,借这个机会试一下效率更高的 PHP-FPM

以下是fabric脚本:

def init_nmp():
    install_nginx()
    install_php()
    install_phpfpm()
 
def install_nginx():
    sudo("add-apt-repository ppa:nginx/stable")
    sudo("apt-get update")
    sudo("apt-get -y -q install nginx-full nginx-common")
 
def install_php():
    # More packages upon request
    sudo("apt-get -y -q --force-yes install php5-cli php5-cgi php5-mysql")
    sudo("apt-get -y -q --force-yes install php5-mcrypt libmcrypt mcrypt") 
 
def install_phpfpm():
    # TODO: use canonical php-fpm package when available
    sudo("add-apt-repository ppa:brianmercer/php")
    sudo("apt-get update")
    sudo("apt-get -y -q install php5-fpm")

/etc/php5/fpm/php5-fpm.conf里将tcp修改成unix socket方式,单机情况下性能更好。

listen = /var/run/php5-fpm.sock
;listen = 127.0.0.1:9000

Nginx里的配置:

location ~ \.php$ { 
    try_files $uri = 404; 
    include /etc/nginx/fastcgi_params; 
    fastcgi_pass unix:/var/run/php5-fpm.sock; 
    fastcgi_index index.php; 
 
    fastcgi_split_path_info         ^(.+\.php)(.*)$; 
    include fastcgi_params; 
    fastcgi_intercept_errors        on; 
    fastcgi_ignore_client_abort     off; 
    fastcgi_connect_timeout         60; 
    fastcgi_send_timeout            180; 
    fastcgi_read_timeout            180; 
    fastcgi_buffer_size             128k; 
    fastcgi_buffers             4   256k; 
    fastcgi_busy_buffers_size       256k; 
    fastcgi_temp_file_write_size    256k; 
}

通过RopeVIM在VIM中实现Python自动完成

发表于2009年12月12日

ropevim可以实现在vim中自动完成,自动import等功能。
参考: http://rope.sourceforge.net/ropevim.html

下载几个rope,ropevim,ropemode:

mkdir ~/install/ropehg
hg clone http://bitbucket.org/agr/rope/ ~/install/ropehg/rope
hg clone http://bitbucket.org/agr/ropevim/ ~/install/ropehg/ropevim
hg clone http://bitbucket.org/agr/ropemode/ ~/install/ropehg/ropemode

可以选择安装:

cd ~/install/ropehg/rope  
python setup.py install
cd ~/install/ropehg/ropevim  
python setup.py install
cd ~/install/ropehg/ropemode  
python setup.py install

或者在 .vimrc 中添加下面的代码:

let $PYTHONPATH .= ":/Users/liwen/install/ropehg/rope:/Users/liwen/install/ropehg/ropemode:/Users/liwen/install/ropehg/ropevim"
source /Users/liwen/install/ropehg/ropevim/ropevim.vim

配置ropevim的代码如下

let ropevim_codeassist_maxfixes=10
let ropevim_guess_project=1
let ropevim_vim_completion=1
let ropevim_enable_autoimport=1
let ropevim_extended_complete=1
 
function! CustomCodeAssistInsertMode()
    call RopeCodeAssistInsertMode()
    if pumvisible()
        return "\<C-L>\<Down>"
    else
        return ''
    endif
endfunction
 
function! TabWrapperComplete()
    let cursyn = synID(line('.'), col('.') - 1, 1)
    if pumvisible()
        return "\<C-Y>"
    endif
    if strpart(getline('.'), 0, col('.')-1) =~ '^\s*$' || cursyn != 0
        return "\<Tab>"
    else
        return "\<C-R>=CustomCodeAssistInsertMode()\<CR>"
    endif
endfunction
 
inoremap <buffer><silent><expr> <Tab> TabWrapperComplete()

自动完成直接可以用,但 RopeRename 不工作,可能是工程太大,分起来比较费劲。还不错。

PS:
1. hg – mercurial
2. 如果遇到以下错误

Error detected while processing function LoadRope:
line    1:
E319: Sorry, the command is not available in this version: python << EOF
line    2:
E492: Not an editor command: import ropevim
line    3:
E492: Not an editor command: EOF
Press ENTER or type command to continue

可能由于vim没有启用python支持,可以打开一个buffer,在命令模式下输入

:python print "hello"

如能正常打印,则配置正确,否则需要重新编译或者安装python支持

sudo port install vim +python26
sudo port install mvim +python26

Good luck!!

将Python程序编译并转换成Windows可执行程序

发表于2009年3月10日

因为要在桃园学校的电脑上安装rur-ple,Pockey和Fred翻译了主程序和前三节课程,rur-ple网站的win32安装包没法merge到一起。所以我重新打一个临时的包。

在编译和打包之前需要安装下面的包:

Python2.5
http://www.python.org/download/releases/

wxPython 2.6
http://www.wxpython.org/download.php#binaries
http://sourceforge.net/projects/wxpython/files/wxPython/2.6.4.0/wxPython2.6-win32-unicode-2.6.4.0-py25.exe/download

py2exe 0.6.5 – 第一个支持Python2.5的版本
http://www.py2exe.org/

编译程序

参照:http://effbot.org/zone/python-compile.htm

进入要编译的python文件所在目录如下。

D:\sunlw\projects\ygclub\teaching\rurple1.0rc3>python
Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import compileall
>>> compileall.compile_dir("./", force=1)

编译完成后运行一下,确认正常。

D:\sunlw\projects\ygclub\teaching\rurple1.0rc3>rur_start.py

貌似运行起来快了一点。

将程序打包成exe

参照:http://www.py2exe.org/index.cgi/Tutorial
添加setup.py文件如下 (http://www.py2exe.org/index.cgi/Tutorial?action=AttachFile&do=view&target=setup.py)

from distutils.core import setup
import py2exe
setup(console=['rur_start.py'])

然后执行

D:\sunlw\projects\ygclub\teaching\rurple1.0rc3>python setup.py py2exe

运行exe程序试试

D:\sunlw\projects\ygclub\teaching\rurple1.0rc3>.\dist\rur_start.exe

成功。

安装包

另外我简单的将编译好的文件用7zip打成自解压程序。

注:
尽量保证依赖的库版本低一些,方便一些安装Windows 2000的电脑使用。