debian 下安装 nginx + uWSGI

编译安装 nginx
sudo aptitude install gcc g++ libpcre3-dev libssl-dev

wget http://nginx.org/download/nginx-0.8.54.tar.gz
tar xzvf nginx-0.8.54.tar.gz
cd nginx-0.8.54/
./configure \
–prefix=/home/gamexg/web \
–sbin-path=/home/gamexg/web/sbin/nginx \
–conf-path=/home/gamexg/web/etc/nginx/nginx.conf \
–error-log-path=/home/gamexg/web/var/log/nginx/error.log \
–pid-path=/home/gamexg/web/var/run/nginx/nginx.pid \
–lock-path=/home/gamexg/web/var/lock/nginx.lock \
–user=nginx \
–group=nginx \
–with-http_gzip_static_module \
–http-log-path=/home/gamexg/web/var/log/nginx/access.log \
–http-client-body-temp-path=/home/gamexg/web/var/tmp/nginx/client/ \
–http-proxy-temp-path=/home/gamexg/web/var/tmp/nginx/proxy/ \
–http-fastcgi-temp-path=/home/gamexg/web/var/tmp/nginx/fcgi/

make && make install

配置nginx
增加一段记录
location /site1 {
uwsgi_pass 127.0.0.1:9000;
include uwsgi_params;
}

编译安装 uWSGI

sudo aptitude install python-dev libxml2-dev
wget http://projects.unbit.it/downloads/uwsgi-0.9.6.8.tar.gz
tar zxfv uwsgi-0.9.6.8.tar.gz
cd uwsgi-0.9.6.8/
make

配置 django 使用 uWSGI
gamexg@vps1:~/web$ mkdir site
gamexg@vps1:~/web$ cd site
gamexg@vps1:~/web/site$ mkdir site1
gamexg@vps1:~/web/site$ cd site1/
gamexg@vps1:~/web/site/site1$ mkdir www
gamexg@vps1:~/web/site/site1$ mkdir www/static
gamexg@vps1:~/web/site/site1$ django-admin startproject site1
gamexg@vps1:~/web/site/site1$ cd site1/
gamexg@vps1:~/web/site/site1/site1$ ./manage.py startapp app1
gamexg@vps1:~/web/site/site1/site1$ vi myapp.py
gamexg@vps1:~/web/site/site1/site1$ cat myapp.py
import os
os.environ[‘DJANGO_SETTINGS_MODULE’] = ‘test1.settings’
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()

vi uwsgi.xml

127.0.0.1:9000
true /home/gamexg/web/var/uwsgi.pid 3 /home/gamexg/web/site/site1/site1 /home/gamexg/web/site/site1 myapp

启动
/home/gamexg/web/uwsgi-0.9.6.8/uwsgi -x /home/gamexg/web/site/site1/uwsgi.xml

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) »

Gentoo 问题:checking for pygtk 2.8.0 installed for python 2.4… not found configure: error: required pygtk version not found

安装 gnome 时出现错误,内容:
checking for pygtk 2.8.0 installed for python 2.4… not found
configure: error: required pygtk version not found

这个应该是升级到 python2.5 后,没有运行 python-updater 的原因。

No comment »

web.py 文档中文翻译:web.py 模板系统 (代码名称templetor)

原文:web.py templating system (codename: templetor)

There are almost as many Python templating systems as there are web frameworks (and, indeed, it seems like many templating systems are adopting web framework-like features), so it is with some trepidation that I work on a new one. Sadly, again I find that my requirements are met by nothing else:
Python 模板系统几乎和web框架一样多(甚至一些 web 框架的特色是拥有多个模板系统。)我总是带着忧虑使用一个新的。令人沮丧的,但是我发现我只需要:

1. The templating system has to look decent. No crud.
1. 这个模板系统看起来不错。不混乱。
2. Reuse Python terms and semantics as much as possible.
2. 尽可能的使用 Python 关键字和语法。
3. Expressive enough to do real computation.
3. 充足的表达式用于真正使用
4. Usable for any text language, not just HTML and XML.
4. 可用于任何文本语言,不要只支持 HTML 和 XML。

And requirements for the implementation as well:

和良好的可用性:

1. Sandboxable so that you can let untrusted users write templates.
1. 沙盒支持,使得你可以允许未信任的用户写模板。
2. Simple and fast implementation.
2. 简单和快速的使用

So here’s my entry.
那么此时我参与。
Variable substitution
替换变量

[coolcode lang=”python”]
Look, a $string.
Hark, an ${arbitrary + expression}.
Gawk, a $dictionary[key].function(‘argument’).
Cool, a $(limit)ing.

Stop, \$money isn’t evaluated.
[/coolcode]

We use basically the same semantics as (rejected) PEP 215. Variables can go anywhere in a document.
我们使用基本上和(不合格?) PEP 215 一样的语义。变量可以在文档的任何地方。
Newline suppression
新行抑制

[coolcode lang=”python”]
If you put a backslash \
at the end of a line \
(like these) \
then there will be no newline.
[/coolcode]

renders as all one line.
所有的显示在一行。
Expressions
表达式

[coolcode lang=”python”]
Here are some expressions:

$for var in iterator: I like $var!

$if times > max:
Stop! In the name of love.
$else:
Keep on, you can do it.
[/coolcode]

That’s all, folks.

All your old Python friends are here: if, while, for, else, break, continue, and pass also act as you’d expect. (Obviously, you can’t have variables named any of these.) The Python code starts at the $ and ends at the :. The $ has to be at the beginning of the line, but that’s not such a burden because of newline suppression (above).
你所有的旧的 Python 朋友在这里:if, while, for, else, break, continue, 和 pass 也为你预期的动作。(明显你不能将变量名称设置为这些。)这些 Python 代码以 $ 开头,以 : 结尾。 $ 在行开始位置,只是叠句因为新行抑制所以不是这样(上面)

Also, we’re very careful about spacing — all the lines will render with no spaces at the beginning. (Open question: what if you want spaces at the beginning?) Also, a trailing space might break your code.
同样,我们非常小心空白 – 所有的行会呈现为开始出没有空白。(问题:如果你需要行开始出有空白怎么做?)同样,结尾处的空白可终止你的代码。

There are a couple changes from Python: for and while now take an else clause that gets called if the loop is never evaluated.
有两个和python不同的更改:for 和 while 现在获得 else 子句,它将在从未执行循环体内代码时执行。

(Possible feature to add: Django-style for loop variables.)
(可能增加的特征:Django-style 循环变量)
Comments
注释

[coolcode lang=”python”]
$# Here’s where we hoodwink the folks at home:

Please enter in your deets:

CC: [ ] $#this is the important one
SSN: $#Social Security Number#$ [ ]
[/coolcode]

Comments start with $# and go to #$ or the end of the line, whichever is first.
Code

注释开始与 $# , 结束与 #$ 或行结尾。

NOTE: This feature has not been implemented in the current web.py implementation of templetor.
注释:这个特征不受到通用的支持。

[coolcode lang=”python”]
Sometimes you just need to break out the Python.

$ mapping = {
$ ‘cool’: [‘nice’, ‘sweet’, ‘hot’],
$ ‘suck’: [‘bad’, ‘evil’, ‘awful’]
$ }

Isn’t that $mapping[thought]?
That’s$ del mapping $ fine with me.

$ complicatedfunc()

$ for x in bugs:
$ if bug.level == ‘severe’:
Ooh, this one is bad.
$ continue
And there’s $x…
[/coolcode]

Body of loops have to be indented with exactly 4 spaces.
循环体的缩进格式是4个空白。

Code begins with a $ and a space and goes until the next $ or the end of the line, whichever comes first. Nothing ever gets output if the first character after the $ is a space (so complicatedfunc above doesn’t write anything to the screen like it might without the space).
代码开始与 $ 和 一个空白 ,直到下一个 $ 或者 行结束。绝不输出$之后的第一个空白(那么执行上面代码绝不输出空白)
Python integration
Python 集成

A template begins with a line like this:
一个模板以这个一样的行开始:

[coolcode lang=”python”]
$def with (name, title, company=’BigCo’)
[/coolcode]

which declares that the template takes those arguments. (The with keyword is special, like def or if.)
声明使用哪些参数。(with 关键字是专用的, like def or if.)

Don’t forget to put spaces in the definition
不要忘记为这个定义放置空格

The following will not work:
下面的必定不能工作:

[coolcode lang=”python”]
$def with (name,title,company=’BigCo’)
[/coolcode]

Inside Python, the template looks like a function that takes these arguments. It returns a storage object with the special property that evaluating it as a string returns the value of the body of the template. The elements in the storage object are the results of the defs and the sets.
这个模板的样子像 Python 内部一个程序使用这些参数。它返回一个和这个模板相关的对象,这个对象模仿字符串的行为。The elements in the storage object are the results of the defs and the sets.

Perhaps an example will make this clearer. Here’s a template, “entry”:
大概一个示例更清晰。像这个例子,‘entry’:

[coolcode lang=”python”]
$def with (post)

$var title: $post.title

$markdown(post.body)

[/coolcode]

Here’s another; “base”:
这里有另外一个;’base’:

[coolcode lang=”python”]
$def with (self)

$self.title

$self.title

$:self
[/coolcode]

Now let’s say we compile both from within Python, the first as entry, the second as base. Here’s how we might use them:
现在假定说我们在 Pyhon 中使用两者,第一个是 entry,第二个是 base。我们应该使用:

[coolcode lang=”python”]
print base( entry( post ) )
[/coolcode]

entry takes the argument post and returns an object whose string value is a bit of HTML showing the post with its title in the property title. base takes this object and places the title in the appropriate place and displays the page itself in the body of the page. The Python code prints out the result.

_Where did markdown come from? It wasn’t passed as an argument._ You can pass a list of functions and variables to the template compiler to be made globally available to templates. Why $:self? See below

Here’s an example:

[coolcode lang=”python”]
import template
render = template.render(‘templates/’)
template.Template.globals[‘len’] = len

print render.base(render.message(‘Hello, world!’))
[/coolcode]

The first line imports templetor. The second says that our templates are in the directory templates/. The third give all our templates access to the len function. The fourth grabs the template message.html, passes it the argument ‘Hello, world!’, passes the result of rendering it to the template base.html and prints the result. (If your templates don’t end in .html or .xml, templetor will still find them, but it won’t do its automatic HTML-encoding.)

Turning Off Filter

By default template.render will use web.websafe filter to do HTML-encoding. To turn it off, put a : after the $ as in:

[coolcode lang=”python”]
$:form.render()
[/coolcode]

Output from form.render() will be displayed as is.

[coolcode lang=”python”]
$:fooBar $# fooBar = lorem ipsum
[/coolcode]

Output from variable in template will be displayed as is.
Including / nesting templates

If you want to nest one template within another, you nest the render() calls, and then include the variable (unfiltered) in the page. In your handler:

[coolcode lang=”python”]
print render.foo(render.bar())
[/coolcode]

or (to make things a little more clear):

[coolcode lang=”python”]
barhtml = render.bar()
print render.foo(barhtml)
[/coolcode]

Then in the template foo.html:

[coolcode lang=”python”]
$def with (bar)
html goes here
$:bar
more html
[/coolcode]

This replaces the $:bar with the output of the render.bar() call (which is why it must be $:/unfiltered, so that you get un-encoded HTML (unless you want something else of course)). You can pass variables in, in the same way:

[coolcode lang=”python”]

print render.foo(render.bar(baz), qux)
[/coolcode]

In the template bar (bar.html):

[coolcode lang=”python”]
$def with (baz)
bar stuff goes here + baz
[/coolcode]

In template foo (foo.html):

[coolcode lang=”python”]
$def with (bar, qux)
html goes here
$:bar
Value of qux is $qux
[/coolcode]

No comment »

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 »