Archive for python

Windows 下安装 Trac,并配置使用Mercurial hg

安装 python2.6 。
http://pypi.python.org/pypi/setuptools/ 下载安装 setuptools 。
执行下面的命令安装 Trac 。

easy_install –always-unzip Trac

现在 Trac 已经安装完毕了,该安装 Mercurial hg 插件了。

http://mercurial.selenic.com/wiki/Download 下载 Mercurial hg 的源代码,并执行setup.py install 来安装(python 2.5 需要 Visual Studio 2005来编译,python 2.6 需要Visual Studio 2008来编译。按官方的说明也可以使用官方发布的Windows二进制版本)。还要注意 Mercurial hg 需要是0.9.5以上版本。
用svn 取出 http://svn.edgewall.com/repos/trac/sandbox/mercurial-plugin-0.11(地址已修改为 http://svn.edgewall.org/repos/trac/plugins/0.11/mercurial-plugin) 目录,并执行 setup.py install 来安装 Trac 的 hg 插件。

现在环境意见建立完毕,开始建立项目了。

执行下面的命令建立 Trac 项目。

trac-admin D:\项目路径 initenv

执行中会提示版本控制系统的类型,直接输入hg就可以。接着会询问版本库的位置,直接输入绝对路径就可以。最后向 D:\项目路径\conf\trac.ini 文件添加以下内容来启用 Mercurial hg 插件。

[trac]
repository_type = hg
repository_dir = /path/to/my/hg/repository

[hg]
# — Show revision number in addition to the changeset hash
show_rev = yes

# — Changeset hash format
node_format = short
# hex: Show the full SHA1 hash
# short: Show a shortened hash for the changesets

现在项目已经建立,可以执行下面的命令来运行项目。然后就可以访问 http://127.0.0.1:8000 来查看项目了。

tracd –port 8000 D:\项目路径

汉化 wiki 。
取出 http://trac-hacks.org/svn/zoomquiettranslation/trunk/0.11.x,并执行以下命令。

trac-admin D:\项目路径 wiki load default-pages/

然后将 ZhTracGuideToc.py 文件拷到 D:\项目路径\plugins 目录下。最后向 D:\项目路径\conf\trac.ini 增加以下内容。

[mainnav]
wiki.href = /wiki/ZhWikiStart

[metanav]
help.href = /wiki/ZhTracGuide

好了,现在就汉化完毕了。

默认Trac没有任何帐号,需要运行下面的命令增加帐号并赋予其全部权限。

>htpasswd -c 项目路径\conf\.htpasswd gamexg 密码
>trac-admin 项目路径 permission add gamexg TRAC_ADMIN

现在 gamexg 用户已经拥有和全部权限,可以使用下面的命令启动 Trac 了。

tracd –hostname=localhost -p 8000 –basic-auth=项目名称,项目路径\conf\.htpasswd,项目名称 项目路径

例子:

tracd -s –basic-auth=trac,trac/conf/.htpasswd, –port 8000 trac

PS:使用中发现utf8文件中文显示有问题。从网上查了一下资料,发现为项目配置文件(项目目录\conf\trac.ini)设置以下内容就可以解决中文utf8文件乱码的问题。

default_charset=utf-8

如果有混合编码可以参考这里TRAC中文显示乱码再解决,为不同的文件设置不同的编码。

[mimeviewer]
#mime_map=text/plain; charset=gbk:c:txt:TXT,
mime_map=text/x-php; charset=utf-8:php
tab_width=4

参考:
Trac Install
http://trac.edgewall.org/wiki/TracInstall
Trac Mercurial
http://trac.edgewall.org/wiki/TracMercurial#TracBrowserchangesin0.11
Trac+subversion拥有强大的bug管理能力
http://www.uml.org.cn/pzgl/200909258.asp

No comment »

使用Python gdata 操作谷歌网络相册

下面是一个使用python gdata 上传图片并获得图片地址的简单例子。需要gdata库。

[py]
In [2]: import gdata.photos, gdata.photos.service
In [3]: pws = gdata.photos.service.PhotosService()
# 下面输入谷歌的帐号
In [4]: pws.ClientLogin(帐号,密码)
In [6]: albums = pws.GetUserFeed()
In [7]: for album in albums.entry:
…: print ‘title: %s, number of photos: %s, id: %s’ % (album.title.text,
…: album.numphotos.text, album.gphoto_id.text)
…:
title: uptest, number of photos: 0, id: 相册ID
title: XXX, number of photos: 1, id: XXX
title: XXX, number of photos: 10, id: XXX

# 获得某个相册的全部照片
In [X]: photos = pws.GetFeed(albums.entry[0].GetPhotosUri()).entry
In [X]: for p in photos:
print ‘t:%s\r\nurl:%s’ %(p.title.text,p.GetMediaURL())
t:New Photo
url:http://lh3.ggpht.com/_?/?/?/?/New%20Photo.jpg

In [8]: import urllib
In [9]: f1 = urllib.urlopen(‘来源URL’)
In [10]: f1.name=’aaaaaaa’

In [15]: album_url = ‘/data/feed/api/user/%s/albumid/%s’ % (‘default’, 相册ID)

# 这里使用的是句柄,也可以直接输入本地文件路径
# content_type需要根据图片类型变更(默认是image/jpeg)。
In [21]: photo = pws.InsertPhotoSimple(album_url, ‘New Photo’,’文本必须是utf8编码的str字符串,unicode 字符串乱码。’, f1, content_type=f1.info().type)

# 获得图片的地址,可以用于外连。(即使设置为非公开的图片也可以使用下面的连接匿名访问。)
In [23]: photo.GetMediaURL()
Out[23]: ‘http://lh3.ggpht.com/_?/?/?/?/?.jpg’

# 获得缩略图
In [25]: for th in photo.media.thumbnail:
….: print th.url
http://lh3.ggpht.com/_?/?/?/?/s72/?.jpg
http://lh3.ggpht.com/_?/?/?/?/s144/?.jpg
http://lh3.ggpht.com/_?/?/?/?/s288/?.jpg

[/py]

参考:
http://code.google.com/intl/zh-CN/apis/picasaweb/developers_guide_python.html

No comment »

gentoo python 下使用 python3 出现 ImportError: No module named _sqlite3 错误的解决办法。

默认 gentoo 下 python 不能使用 sqlite3,会出现 ImportError: No module named _sqlite3 错误。
解决办法是增加 sqlite USE 标志并重新编译 python 。虽然有 sqlite3 这个use标志,但是 python 不能识别。建议只为python增加sqlite标志。执行
# echo “dev-lang/python sqlite” >> /etc/portage/package.use
就可以增加use标志。

gamexg@GGentoo ~ $ python
Python 2.5.2 (r252:60911, Oct 31 2008, 10:01:00)
[GCC 4.1.2 (Gentoo 4.1.2 p1.1)] on linux2
Type “help”, “copyright”, “credits” or “license” for more information.
>>> import sqlite3
Traceback (most recent call last):
File “”, line 1, in
File “/usr/lib/python2.5/sqlite3/__init__.py”, line 24, in
from dbapi2 import *
File “/usr/lib/python2.5/sqlite3/dbapi2.py”, line 27, in
from _sqlite3 import *
ImportError: No module named _sqlite3

Comments (1) »

Python 自动补全 大全(IPython,readline,vim)

如果想使用交互式命令行自动补全,建议使用Ipython。

IPython 比使用
import readline, rlcompleter; readline.parse_and_bind(“tab: complete”)
启动的自动补全更好些。例如import 时也可以自动补全模板名。

想为vim启动自动补全需要下载插件。
http://vim.sourceforge.net/scripts/script.php?script_id=850
下载后将 pydiction 文件解压到 ~/.vim/tools 目录下。
然后对.vimc 增加以下内容

” python auto-complete code
” Typing the following (in insert mode):
” os.lis
” will expand to:
” os.listdir(
” Python 自动补全功能,只需要反覆按 Ctrl-N 就行了
if has(“autocmd”)
autocmd FileType python set complete+=k~/.vim/tools/pydiction
endif

现在使用Ctr+N 就可以自动补全了。

Comments (2) »

Pyrex 安装的小问题: MinGW 配置修改

为 pyrex 安装 MinGW 需要将
mingw\lib\gcc\mingw32\3.2.4\specs
文件里的”-lmsvcrt” 修改为 “-lmsvcr71”.

原因是 python 使用 msvcr71 ,使用不同版本的库会影响稳定性。

No comment »

Windows 下以 nginx proxy模式运行 web.py

注意:更好的方式是使用WSGI,但是没有发现windows版本(我也只是开发用,实际建议使用linux+WSGI)。这里使用的是代理模式。(windows 下最好使用fastcgi模式,参考Windows 下以 nginx + fastcgi 运行 Django 或 web.py。这里只是一个功能说明,如果后端使用apache等不支持 fastcgi 等模式时可以使用本方法。)

从 http://www.saddi.com/software/flup/dist/ 下载 flup 并执行 setup.py install 安装。
用压缩软件打开 flup-1.0.1-py2.5.egg 修改 fcgi_base.py 文件,将 isFCGI = True 改成 isFCGI = False 并注释掉以下代码:
[coolcode]
sock = socket.fromfd(FCGI_LISTENSOCK_FILENO, socket.AF_INET,
socket.SOCK_STREAM)
try:
sock.getpeername()
except socket.error, e:
if e[0] == errno.ENOTSOCK:
# Not a socket, assume CGI context.
isFCGI = False
elif e[0] != errno.ENOTCONN:
raise
[/coolcode]
从 http://www.kevinworthington.com/category/computers/nginx/ 下载 nginx Windows 版本的安装程序。
运行并安装。
打开配置文件nginx/conf/nginx.conf 修改为:

[coolcode download=”nginx.conf”]
#user nobody;
worker_processes 1;

#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;

#pid logs/nginx.pid;

events {
worker_connections 64;
}

http {
include mime.types;
default_type application/octet-stream;

#log_format main ‘$remote_addr – $remote_user [$time_local] $request ‘
# ‘”$status” $body_bytes_sent “$http_referer” ‘
# ‘”$http_user_agent” “$http_x_forwarded_for”‘;

#access_log logs/access.log main;

sendfile on;
#tcp_nopush on;

#keepalive_timeout 0;
keepalive_timeout 65;

#gzip on;

server {
listen 80;
server_name localhost;

root /cygdrive/D/html;
index index.html index.htm;

charset utf-8;

#access_log logs/host.access.log main;

# static resources
location ~* ^.+\.(html|jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mid|midi|wav|bmp|rtf|js)$
{
expires 30d;
break;
}

location / {
proxy_pass http://127.0.0.1:8061;
}

#error_page 404 /404.html;

# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}

# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}

# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}

# deny access to .htaccess files, if Apache’s document root
# concurs with nginx’s one
#
#location ~ /\.ht {
# deny all;
#}
}

# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;

# location / {
# root html;
# index index.html index.htm;
# }
#}

# HTTPS server
#
#server {
# listen 443;
# server_name localhost;

# ssl on;
# ssl_certificate cert.pem;
# ssl_certificate_key cert.key;

# ssl_session_timeout 5m;

# ssl_protocols SSLv2 SSLv3 TLSv1;
# ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;
# ssl_prefer_server_ciphers on;

# location / {
# root html;
# index index.html index.htm;
# }
#}

}
[/coolcode]

现在建立a.py 内容是
[coolcode lang=”python” download=”a.py”]
#!/usr/bin/env python
import web
urls = (
‘/.*’, ‘hello’
)
class hello:
def GET(self):
print ‘aaa’
if __name__ == “__main__”: web.run(urls, globals())
[/coolcode]
然后重启 nginx 并执行 a.py 8061

现在就可以访问了。静态文件由nginx负责,动态内容由a.py负责。

主目录为d:\html,定义是:
root /cygdrive/D/html;

附一个参数列表(发现一般是使用include 包含配置文件fastcgi_params):
fastcgi_param QUERY_STRING $query_string;
fastcgi_param REQUEST_METHOD $request_method;
fastcgi_param CONTENT_TYPE $content_type;
fastcgi_param CONTENT_LENGTH $content_length;

fastcgi_param SCRIPT_NAME $fastcgi_script_name;
fastcgi_param REQUEST_URI $request_uri;
fastcgi_param DOCUMENT_URI $document_uri;
fastcgi_param DOCUMENT_ROOT $document_root;
fastcgi_param SERVER_PROTOCOL $server_protocol;

fastcgi_param GATEWAY_INTERFACE CGI/1.1;
fastcgi_param SERVER_SOFTWARE nginx;

fastcgi_param REMOTE_ADDR $remote_addr;
fastcgi_param REMOTE_PORT $remote_port;
fastcgi_param SERVER_ADDR $server_addr;
fastcgi_param SERVER_PORT $server_port;
fastcgi_param SERVER_NAME $server_name;
# PHP only, required if PHP was built with –enable-force-cgi-redirect
fastcgi_param REDIRECT_STATUS 200;

Comments (1) »

Windows 下以 nginx + fastcgi 运行 Django 或 web.py

从 http://www.saddi.com/software/flup/dist/ 下载 flup 并执行 setup.py install 安装。

从 http://www.kevinworthington.com/category/computers/nginx/ 下载nginx Windows版本的安装程序。
运行并安装。
打开配置文件 nginx/conf/nginx.conf 修改为:
[coolcode download=”nginx.conf”]
#user nobody;
worker_processes 1;

#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;

#pid logs/nginx.pid;

events {
worker_connections 64;
}

http {
include mime.types;
default_type application/octet-stream;

#log_format main ‘$remote_addr – $remote_user [$time_local] $request ‘
# ‘”$status” $body_bytes_sent “$http_referer” ‘
# ‘”$http_user_agent” “$http_x_forwarded_for”‘;

#access_log logs/access.log main;

sendfile on;
#tcp_nopush on;

#keepalive_timeout 0;
keepalive_timeout 65;

#gzip on;

server {
listen 80;
server_name localhost;

root /cygdrive/D/html;
index index.html index.htm;

charset utf-8;

#access_log logs/host.access.log main;

# 静态资源
location ~* ^.+\.(html|jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mid|midi|wav|bmp|rtf|js)$
{
expires 30d;
break;
}

location / {
# 指定 fastcgi 的主机和端口
fastcgi_pass 127.0.0.1:8051;
fastcgi_param PATH_INFO $fastcgi_script_name;
fastcgi_param REQUEST_METHOD $request_method;
fastcgi_param QUERY_STRING $query_string;
fastcgi_param CONTENT_TYPE $content_type;
fastcgi_param CONTENT_LENGTH $content_length;
fastcgi_param SERVER_PROTOCOL $server_protocol;
fastcgi_param SERVER_PORT $server_port;
fastcgi_param SERVER_NAME $server_name;
fastcgi_pass_header Authorization;
fastcgi_intercept_errors off;
}

#error_page 404 /404.html;

# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}

# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}

# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}

# deny access to .htaccess files, if Apache’s document root
# concurs with nginx’s one
#
#location ~ /\.ht {
# deny all;
#}
}

# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;

# location / {
# root html;
# index index.html index.htm;
# }
#}

# HTTPS server
#
#server {
# listen 443;
# server_name localhost;

# ssl on;
# ssl_certificate cert.pem;
# ssl_certificate_key cert.key;

# ssl_session_timeout 5m;

# ssl_protocols SSLv2 SSLv3 TLSv1;
# ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;
# ssl_prefer_server_ciphers on;

# location / {
# root html;
# index index.html index.htm;
# }
#}

}
[/coolcode]
现在重启启动 nginx 后在Django项目下执
.\manage.py runfcgi method=threaded host=127.0.0.1 port=8051
就可以了。

这里没有设置 media 目录,现在是以扩展名来分辨是不是转发到Django的程序处理。
想要只允许 nginx 处理media 目录只需要将
location ~* ^.+\.(html|jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mid|midi|wav|bmp|rtf|js)$
换成
location ~ ^/media/
就可以了。

主目录为d:\html,定义是:
root /cygdrive/D/html;

如果运行 web.py 的项目
[coolcode lang=”python” download=”a.py”]
#!/usr/bin/env python
import web
urls = (
‘/.*’, ‘hello’
)
class hello:
def GET(self):
print ‘aaa’
if __name__ == “__main__”: web.run(urls, globals())
[/coolcode]
只需要把执行
.\manage.py runfcgi method=threaded host=127.0.0.1 port=8051
换成执行
a.py 8051 fastcgi
就可以了。

附一个参数列表(发现一般是使用include 包含配置文件fastcgi_params):
fastcgi_param QUERY_STRING $query_string;
fastcgi_param REQUEST_METHOD $request_method;
fastcgi_param CONTENT_TYPE $content_type;
fastcgi_param CONTENT_LENGTH $content_length;

fastcgi_param SCRIPT_NAME $fastcgi_script_name;
fastcgi_param REQUEST_URI $request_uri;
fastcgi_param DOCUMENT_URI $document_uri;
fastcgi_param DOCUMENT_ROOT $document_root;
fastcgi_param SERVER_PROTOCOL $server_protocol;

fastcgi_param GATEWAY_INTERFACE CGI/1.1;
fastcgi_param SERVER_SOFTWARE nginx;

fastcgi_param REMOTE_ADDR $remote_addr;
fastcgi_param REMOTE_PORT $remote_port;
fastcgi_param SERVER_ADDR $server_addr;
fastcgi_param SERVER_PORT $server_port;
fastcgi_param SERVER_NAME $server_name;
# PHP only, required if PHP was built with –enable-force-cgi-redirect
fastcgi_param REDIRECT_STATUS 200;

Comments (1) »

Python类库中文翻译:Socket 对象(只翻译了一点)

17.2.1 Socket Objects

Socket objects have the following methods. Except for makefile() these correspond to Unix system calls applicable to sockets.

accept( )
Accept a connection. The socket must be bound to an address and listening for connections. The return value is a pair (conn, address) where conn is a new socket object usable to send and receive data on the connection, and address is the address bound to the socket on the other end of the connection.

bind( address)
Bind the socket to address. The socket must not already be bound. (The format of address depends on the address family — see above.) Note: This method has historically accepted a pair of parameters for AF_INET addresses instead of only a tuple. This was never intentional and is no longer available in Python 2.0 and later.

close( )
Close the socket. All future operations on the socket object will fail. The remote end will receive no more data (after queued data is flushed). Sockets are automatically closed when they are garbage-collected.

connect( address)
Connect to a remote socket at address. (The format of address depends on the address family — see above.) Note: This method has historically accepted a pair of parameters for AF_INET addresses instead of only a tuple. This was never intentional and is no longer available in Python 2.0 and later.

connect_ex( address)
Like connect(address), but return an error indicator instead of raising an exception for errors returned by the C-level connect() call (other problems, such as “host not found,” can still raise exceptions). The error indicator is 0 if the operation succeeded, otherwise the value of the errno variable. This is useful to support, for example, asynchronous connects. Note: This method has historically accepted a pair of parameters for AF_INET addresses instead of only a tuple. This was never intentional and is no longer available in Python 2.0 and later.

fileno( )
Return the socket’s file descriptor (a small integer). This is useful with select.select().
返回这个套接字的文件描述符(一个 small integer)。它用于 select.select()

Under Windows the small integer returned by this method cannot be used where a file descriptor can be used (such as os.fdopen()). Unix does not have this limitation.
在 Windows 本方法返回的small integer 不能当作一个文件描述符使用(例如 os.fdopen())。 Unix 没有此限制。

getpeername( )
Return the remote address to which the socket is connected. This is useful to find out the port number of a remote IPv4/v6 socket, for instance. (The format of the address returned depends on the address family — see above.) On some systems this function is not supported.

getsockname( )
Return the socket’s own address. This is useful to find out the port number of an IPv4/v6 socket, for instance. (The format of the address returned depends on the address family — see above.)

getsockopt( level, optname[, buflen])
Return the value of the given socket option (see the Unix man page getsockopt(2)). The needed symbolic constants (SO_* etc.) are defined in this module. If buflen is absent, an integer option is assumed and its integer value is returned by the function. If buflen is present, it specifies the maximum length of the buffer used to receive the option in, and this buffer is returned as a string. It is up to the caller to decode the contents of the buffer (see the optional built-in module struct for a way to decode C structures encoded as strings).

listen( backlog)
Listen for connections made to the socket. The backlog argument specifies the maximum number of queued connections and should be at least 1; the maximum value is system-dependent (usually 5).

makefile( [mode[, bufsize]])
Return a file object associated with the socket. (File objects are described in 3.9, “File Objects.”) The file object references a dup()ped version of the socket file descriptor, so the file object and socket object may be closed or garbage-collected independently. The socket must be in blocking mode. The optional mode and bufsize arguments are interpreted the same way as by the built-in file() function; see “Built-in Functions” (section 2.1) for more information.

recv( bufsize[, flags])
Receive data from the socket. The return value is a string representing the data received. The maximum amount of data to be received at once is specified by bufsize. See the Unix manual page recv(2) for the meaning of the optional argument flags; it defaults to zero. Note: For best match with hardware and network realities, the value of bufsize should be a relatively small power of 2, for example, 4096.
从套接字获得数据。返回值是字符串格式的接收到的数据。一次接受数据的最大数量是 bufsize。参数 flags 的作用参考 Unix manual 的 recv(2) 页面,它的默认值是0。注意:最好与硬件和网络实现比配,bufsize 建议使用一个小值,例如:4096。

recvfrom( bufsize[, flags])
Receive data from the socket. The return value is a pair (string, address) where string is a string representing the data received and address is the address of the socket sending the data. The optional flags argument has the same meaning as for recv() above. (The format of address depends on the address family — see above.)
从套接字获得数据。返回值是(string,address),string 是字符串格式接收到的数据,address 是那个地址发送的这个数据。参数 flags 和 recv() 一样。(地址格式依赖于协议类型。)

recvfrom_into( buffer[, nbytes[, flags]])
Receive data from the socket, writing it into buffer instead of creating a new string. The return value is a pair (nbytes, address) where nbytes is the number of bytes received and address is the address of the socket sending the data. See the Unix manual page recv(2) for the meaning of the optional argument flags; it defaults to zero. (The format of address depends on the address family — see above.) New in version 2.5.

recv_into( buffer[, nbytes[, flags]])
Receive up to nbytes bytes from the socket, storing the data into a buffer rather than creating a new string. If nbytes is not specified (or 0), receive up to the size available in the given buffer. See the Unix manual page recv(2) for the meaning of the optional argument flags; it defaults to zero. New in version 2.5.
从 socket 接收 nbytes 字节的数据,储存数据到 buffer 而不是创建一个新的字符串。如果 nbytes 没有指定(或者为0),那么接收buffer 可用空间的数据。flags 参数请查看 Unix manual recv(2) 页面,它的默认值是0。2.5版本新增。

send( string[, flags])
Send data to the socket. The socket must be connected to a remote socket. The optional flags argument has the same meaning as for recv() above. Returns the number of bytes sent. Applications are responsible for checking that all data has been sent; if only some of the data was transmitted, the application needs to attempt delivery of the remaining data.
向这个套接字发送数据。这个套接字必须已经连接远程套接字。flags 选项请参考recv()。返回值是已发送的字节数。应用程序有责任检查所有数据是是否全部发送。如果只有部分数据被发送,那么应用程序必须重新发送剩余的数据。

sendall( string[, flags])
Send data to the socket. The socket must be connected to a remote socket. The optional flags argument has the same meaning as for recv() above. Unlike send(), this method continues to send data from string until either all data has been sent or an error occurs. None is returned on success. On error, an exception is raised, and there is no way to determine how much data, if any, was successfully sent.
向这个套接字发送数据。这个套接字必须已经连接远程套接字。flags 选项请参考recv()。不同于 send(),本方法一直发送数据知道全部数据发送成功或者发生错误。成功是返回 None。发生错误时,一个异常被引发。不限制大量数据,即使大量数据也可以安全发送。

sendto( string[, flags], address)
Send data to the socket. The socket should not be connected to a remote socket, since the destination socket is specified by address. The optional flags argument has the same meaning as for recv() above. Return the number of bytes sent. (The format of address depends on the address family — see above.)

setblocking( flag)
Set blocking or non-blocking mode of the socket: if flag is 0, the socket is set to non-blocking, else to blocking mode. Initially all sockets are in blocking mode. In non-blocking mode, if a recv() call doesn’t find any data, or if a send() call can’t immediately dispose of the data, a error exception is raised; in blocking mode, the calls block until they can proceed. s.setblocking(0) is equivalent to s.settimeout(0); s.setblocking(1) is equivalent to s.settimeout(None).

settimeout( value)
Set a timeout on blocking socket operations. The value argument can be a nonnegative float expressing seconds, or None. If a float is given, subsequent socket operations will raise an timeout exception if the timeout period value has elapsed before the operation has completed. Setting a timeout of None disables timeouts on socket operations. s.settimeout(0.0) is equivalent to s.setblocking(0); s.settimeout(None) is equivalent to s.setblocking(1). New in version 2.3.

gettimeout( )
Return the timeout in floating seconds associated with socket operations, or None if no timeout is set. This reflects the last call to setblocking() or settimeout(). New in version 2.3.

Some notes on socket blocking and timeouts: A socket object can be in one of three modes: blocking, non-blocking, or timeout. Sockets are always created in blocking mode. In blocking mode, operations block until complete. In non-blocking mode, operations fail (with an error that is unfortunately system-dependent) if they cannot be completed immediately. In timeout mode, operations fail if they cannot be completed within the timeout specified for the socket. The setblocking() method is simply a shorthand for certain settimeout() calls.

Timeout mode internally sets the socket in non-blocking mode. The blocking and timeout modes are shared between file descriptors and socket objects that refer to the same network endpoint. A consequence of this is that file objects returned by the makefile() method must only be used when the socket is in blocking mode; in timeout or non-blocking mode file operations that cannot be completed immediately will fail.

Note that the connect() operation is subject to the timeout setting, and in general it is recommended to call settimeout() before calling connect().

setsockopt( level, optname, value)
Set the value of the given socket option (see the Unix manual page setsockopt(2)). The needed symbolic constants are defined in the socket module (SO_* etc.). The value can be an integer or a string representing a buffer. In the latter case it is up to the caller to ensure that the string contains the proper bits (see the optional built-in module struct for a way to encode C structures as strings).

shutdown( how)
Shut down one or both halves of the connection. If how is SHUT_RD, further receives are disallowed. If how is SHUT_WR, further sends are disallowed. If how is SHUT_RDWR, further sends and receives are disallowed.

Note that there are no methods read() or write(); use recv() and send() without flags argument instead.

Socket objects also have these (read-only) attributes that correspond to the values given to the socket constructor.

family
The socket family. New in version 2.5.

type
The socket type. New in version 2.5.

proto
The socket protocol. New in version 2.5.

No comment »

Python类库中文翻译:select — 等待 I/O 完成

15.1 select — Waiting for I/O completion

This module provides access to the select() and poll() functions available in most operating systems. Note that on Windows, it only works for sockets; on other operating systems, it also works for other file types (in particular, on Unix, it works on pipes). It cannot be used on regular files to determine whether a file has grown since it was last read.
这个模块提供的 select() 和 poll() 方法可用于大部分操作系统。注意:在 Windows 下,它只能用于 sockets ;在其他系统下,它也可以用于其他类型(特别在 Unix 下,它还可以用于 管道)。它不能用来确定是否完成上次的对普通文件执行的读取操作。

The module defines the following:
这个模块定义下列内容:

exception error
异常错误
The exception raised when an error occurs. The accompanying value is a pair containing the numeric error code from errno and the corresponding string, as would be printed by the C function perror().
在发生错误将引发异常。accompanying 值包含错误代码和错误描述文本,用于使用 C 程序 perror() 打印。

poll( )
(Not supported by all operating systems.) Returns a polling object, which supports registering and unregistering file descriptors, and then polling them for I/O events; see section 15.1.1 below for the methods supported by polling objects.
(所有系统不支持。)

select( iwtd, owtd, ewtd[, timeout])
This is a straightforward interface to the Unix select() system call. The first three arguments are sequences of `waitable objects’: either integers representing file descriptors or objects with a parameterless method named fileno() returning such an integer. The three sequences of waitable objects are for input, output and `exceptional conditions’, respectively. Empty sequences are allowed, but acceptance of three empty sequences is platform-dependent. (It is known to work on Unix but not on Windows.) The optional timeout argument specifies a time-out as a floating point number in seconds. When the timeout argument is omitted the function blocks until at least one file descriptor is ready. A time-out value of zero specifies a poll and never blocks.
这对于 Ubix 系统调用 select() 来说是一个简单接口。前三个参数是‘等待对象’;????。这三个参数分别按顺序等待 输入、输出输出和异常状态。允许空数组,但是是否允许三个空序列依赖于平台。(已知支持 Unix 但是不支持 Windows。)timeout 参数接受浮点数表示的秒。如果省略 timeout 着阻塞到至少一个文件描述符准备就绪。timeout 为0表示从不阻塞。
译者注:在对方关闭连接的情况下(CLOSE_WAIT状态)会立即返回,并且处于可读列表里面。但是却会立即读到0长度的数据。建议在检测到连续多次读到0长度数据时关闭连接。

The return value is a triple of lists of objects that are ready: subsets of the first three arguments. When the time-out is reached without a file descriptor becoming ready, three empty lists are returned.
返回值是包含前三个参数里面已准备就绪的对象的3个列表.如果已经超时但是并没有对象准备就绪,那么返回3个空列表

Among the acceptable object types in the sequences are Python file objects (e.g. sys.stdin, or objects returned by open() or os.popen()), socket objects returned by socket.socket().You may also define a wrapper class yourself, as long as it has an appropriate fileno() method (that really returns a file descriptor, not just a random integer). Note: File objects on Windows are not acceptable, but sockets are. On Windows, the underlying select() function is provided by the WinSock library, and does not handle file descriptors that don’t originate from WinSock.
接受的对象类型按次序是 Python 文件对象(例如:sys.stdin 或者 open()或os.popen()返回的对象)或者socket.socket()返回的socket对象。你也可以定义一个类,只要它包含恰当的 fileno() 方法(它其实范围文件描述符,不要只是返回随机数)注意:windows 不接受文件对象,但是接受 sockets。在 windows 下 select() 程序隐式使用 WinSock 库,WinSock 并不支持文件对象句柄。

Subsections

* 15.1.1 Polling Objects

No comment »

Python类库中文翻译:BaseHTTPServer — 基本 HTTP 服务器

This module defines two classes for implementing HTTP servers (Web servers). Usually, this module isn’t used directly, but is used as a basis for building functioning Web servers. See the SimpleHTTPServer and CGIHTTPServer modules.
这个模块定义了两个类用来实现 HTTP 服务器(WEB服务器)。通常本模块不会直接使用。

The first class, HTTPServer, is a SocketServer.TCPServer subclass. It creates and listens at the HTTP socket, dispatching the requests to a handler. Code to create and run the server looks like this:
第一个类,HTTPServer 是一个 SocketServer.TCPServer 的子集。他创建并监听 HTTP 套接字,分配 requests 到处理器(handler)。编码创建并运行这个服务器看起来像这样:

def run(server_class=BaseHTTPServer.HTTPServer,
handler_class=BaseHTTPServer.BaseHTTPRequestHandler):
server_address = (”, 8000)
httpd = server_class(server_address, handler_class)
httpd.serve_forever()

class HTTPServer( server_address, RequestHandlerClass)
This class builds on the TCPServer class by storing the server address as instance variables named server_name and server_port. The server is accessible by the handler, typically through the handler’s server instance variable.

class BaseHTTPRequestHandler( request, client_address, server)
This class is used to handle the HTTP requests that arrive at the server. By itself, it cannot respond to any actual HTTP requests; it must be subclassed to handle each request method (e.g. GET or POST). BaseHTTPRequestHandler provides a number of class and instance variables, and methods for use by subclasses.

这个类在 HTTP 请求到达时处理它。实际上它自身并不能对任何 HTTP 请求作出响应,他必须存在派生类用来处理每一个请求方法(例如 GET 或者 POST)。BaseHTTPRequestHandler 为子集提供许多类变量、实例变量和方法。

The handler will parse the request and the headers, then call a method specific to the request type. The method name is constructed from the request. For example, for the request method “SPAM”, the do_SPAM() method will be called with no arguments. All of the relevant information is stored in instance variables of the handler. Subclasses should not need to override or extend the __init__() method.
这个处理器将分析请求对象和请求头部,然后根据请求类型调用相应的方法。这个方法名称根据请求类型建立。例子:如果请求方法为’SPAM’,那么 do_SOAM() 方法将无可争议的被调用。所有有关信息被存放在实例变量。派生类应该不需要理睬或扩展 __init() 方法。

BaseHTTPRequestHandler has the following instance variables:
BaseHTTPRequestHandler 拥有下列实例值:

client_address
Contains a tuple of the form (host, port) referring to the client’s address.

command
Contains the command (request type). For example, ‘GET’.
包含命令(请求类型)。例子:’GET’。

path
Contains the request path.
包含请求路径。

request_version
Contains the version string from the request. For example, ‘HTTP/1.0’.
包含请求的版本字符串。例子:’HTTP/1.0′

headers
Holds an instance of the class specified by the MessageClass class variable. This instance parses and manages the headers in the HTTP request.

rfile
Contains an input stream, positioned at the start of the optional input data.
包含输入流,从最初可选的输入数据开始。

wfile
Contains the output stream for writing a response back to the client. Proper adherence to the HTTP protocol must be used when writing to this stream.
包含一个用类写入响应的输出流。请遵守 HTTP 协议在适当的时候使用这个流。

BaseHTTPRequestHandler has the following class variables:
BaseHTTPRequestHandler 拥有下列类属性:

server_version
Specifies the server software version. You may want to override this. The format is multiple whitespace-separated strings, where each string is of the form name[/version]. For example, ‘BaseHTTP/0.2’.
指定服务器软件版本。你可以不理睬它。

sys_version
Contains the Python system version, in a form usable by the version_string method and the server_version class variable. For example, ‘Python/1.4’.
包含 Python 程序版本,用于 version_string 方法和 server_version 类变量。例子:’Python/1.4’。

error_message_format
Specifies a format string for building an error response to the client. It uses parenthesized, keyed format specifiers, so the format operand must be a dictionary. The code key should be an integer, specifying the numeric HTTP error code value. message should be a string containing a (detailed) error message of what occurred, and explain should be an explanation of the error code number. Default message and explain values can found in the responses class variable.
指定用于发送给客户端的错误回应使用的格式字符串。使用被括号括主的key格式,所以格式化参数必须包含在一个字典里面。code 键是一个整数,为 HTTP 错误代码。message 是一个字符串,为相信的错误消息。explain 是错误代码的说明。默认 message 和 explain 的值可以在responses 类里面找到。

protocol_version
This specifies the HTTP protocol version used in responses. If set to ‘HTTP/1.1’, the server will permit HTTP persistent connections; however, your server must then include an accurate Content-Length header (using send_header()) in all of its responses to clients. For backwards compatibility, the setting defaults to ‘HTTP/1.0’.
指定HTTP协议版本。如果你设定为’HTTP/1.1’,那么这个服务器支持持久连接。不管什么情况,你的服务器向客户端回应的所有响应(responses)必须包含准确的 Content-Length 头(使用 send_header())。为了向后兼容,默认设置为 ‘HTTP/1.0’ 。

MessageClass
Specifies a rfc822.Message-like class to parse HTTP headers. Typically, this is not overridden, and it defaults to mimetools.Message.

responses
This variable contains a mapping of error code integers to two-element tuples containing a short and long message. For example, {code: (shortmessage, longmessage)}. The shortmessage is usually used as the message key in an error response, and longmessage as the explain key (see the error_message_format class variable).
这个变量包含根据错误代码映射到包含两个长短消息的成员的 tuples 的字典。

A BaseHTTPRequestHandler instance has the following methods:
一个 BaseHTTPRequestHandler 视力拥有下列方法:

handle( )
Calls handle_one_request() once (or, if persistent connections are enabled, multiple times) to handle incoming HTTP requests. You should never need to override it; instead, implement appropriate do_*() methods.
调用 handle_one_request() 一次(如果激活持久连接,则多次)来处理新到达的请求。你应该从来不需要理睬它,而应该使用恰当的 do_*() 方法。

handle_one_request( )
This method will parse and dispatch the request to the appropriate do_*() method. You should never need to override it.
这个处理并分配请求到恰当的 do_*() 方法。你应该从来不需要理睬他。

send_error( code[, message])
Sends and logs a complete error reply to the client. The numeric code specifies the HTTP error code, with message as optional, more specific text. A complete set of headers is sent, followed by text composed using the error_message_format class variable.
为客户端发送一个完整的错误回应并记录它。code 指定了 HTTP 错误代码,可选的 message 提供了更详细的信息。一个完整的响应头被发送后,根据 erroe_message_format 生成的正文被发送。

send_response( code[, message])
Sends a response header and logs the accepted request. The HTTP response line is sent, followed by Server and Date headers. The values for these two headers are picked up from the version_string() and date_time_string() methods, respectively.
发送回应头和记录这个普通请求。HTTP 回应行发送完成后紧跟着发送 Server 和 Date 头。这两个值分别从 version_string() 和 date_time_string() 获得。

send_header( keyword, value)
Writes a specific HTTP header to the output stream. keyword should specify the header keyword, with value specifying its value.
向输出流写入指定的 HTTP 头。keyword 为 HTTP 头键,value 为 HTTP 头的值。

end_headers( )
Sends a blank line, indicating the end of the HTTP headers in the response.
发送一个空白行,标志着回应的 HTTP 头结束。

log_request( [code[, size]])
Logs an accepted (successful) request. code should specify the numeric HTTP code associated with the response. If a size of the response is available, then it should be passed as the size parameter.
记录一个成功的普通请求。code 指定为响应的HTTP代码。如果大小是确定的,那么应该传递到 size 参数。

log_error( …)
Logs an error when a request cannot be fulfilled. By default, it passes the message to log_message(), so it takes the same arguments (format and additional values).
记录什么时间的一个请求出错不能执行。默认,它转发消息到 log_message(),它使用一样参数(format 和 附加的参数)。

log_message( format, …)
Logs an arbitrary message to sys.stderr. This is typically overridden to create custom error logging mechanisms. The format argument is a standard printf-style format string, where the additional arguments to log_message() are applied as inputs to the formatting. The client address and current date and time are prefixed to every message logged.
记录任意格式消息到 sys.stderr。它通常被自定义的日子处理程序覆盖。format 参数是标准的 printf-style 格式字符串,由传入 log_message() 的额外参数用于格式化。客户端地址和当前日期和时间被附加在每一个日志消息前面。

version_string( )
Returns the server software’s version string. This is a combination of the server_version and sys_version class variables.
返回服务软件的版本字符串。这是 server_version 和 sys_version 的组合。

date_time_string( [timestamp])
Returns the date and time given by timestamp (which must be in the format returned by time.time()), formatted for a message header. If timestamp is omitted, it uses the current date and time.
根据 timestamp(必须是time.time()返回的格式) 返回时间和日期。如果 timestamp 不存在,那么它将使用当前日期和时间。

The result looks like ‘Sun, 06 Nov 1994 08:49:37 GMT’. New in version 2.5: The timestamp parameter.
他的结果看起来像’Sun, 06 Nov 1994 08:49:37 GMT’。2.5版本的新功能:timestamp 参数。

log_date_time_string( )
Returns the current date and time, formatted for logging.
返回格式化后的用于日志的当前日期和时间。

address_string( )
Returns the client address, formatted for logging. A name lookup is performed on the client’s IP address.
返回格式化后的用于日志的客户地址。对客户IP地址执行名称查询。
译注:真实使用时建议重写本方法为直接输出IP,执行名称查询会严重影响性能。

See Also:
参考:

Module CGIHTTPServer:
Extended request handler that supports CGI scripts.
扩展请求处理器以支持 CGI 脚本。

Module SimpleHTTPServer:
Basic request handler that limits response to files actually under the document root.
基本请求处理器,限制响应的文件范围为 document 目录之下。

译者注:建议继承者设置 rbufsize = 0 来关闭 self.rfile 的缓冲,用来防止少量数据 POST 时不会被 select.select 识别的问题

Comments (1) »