搭建 Nginx+FastCGI+Webpy 平台开发Python Web应用

web.py is a web framework for Python that is as simple as it is powerful. web.py is in the public domain; you can use it for whatever purpose with absolutely no restrictions.

webpy相比于django很轻量很容易上手。

需要用到easy_install,flup。假设已经装好了NGINX。
安装web.py:
easy_install web.py
配置NGINX(如果需要访问静态文件别忘了自己再单独配一下):
server {
        listen       80;
        server_name  webpy.com;

        root   /home/admin/python/webpy;

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   /usr/local/www/nginx-dist;
        }

        location ~* / {
                fastcgi_pass 127.0.0.1:9002;
                fastcgi_pass_header Authorization;
                fastcgi_intercept_errors off;
                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_PORT       $server_port;
                fastcgi_param SERVER_PROTOCOL   $server_protocol;
                fastcgi_param SERVER_NAME       $server_name;
                fastcgi_param REQUEST_URI       $request_uri;
                fastcgi_param DOCUMENT_URI      $document_uri;
                fastcgi_param DOCUMENT_ROOT     $document_root;
                fastcgi_param SERVER_ADDR       $server_addr;
                fastcgi_param REMOTE_USER       $remote_user;
                fastcgi_param REMOTE_ADDR       $remote_addr;
                fastcgi_param REMOTE_PORT       $remote_port;
                fastcgi_param SERVER_SOFTWARE   "nginx";
        }
    }
编写code.py的代码,一个简单的应用例子,抓取美团网今日团购信息:
#coding=utf-8
import web
import urllib2,re

urls = (
    '/', 'tuangou',
)
app = web.application(urls, globals())

class tuangou:
    def GET(self):
        html = '<head><meta http-equiv="Content-Type" content="text/html;charset=utf-8"></head>'
        html = re.compile(r'<h1>(.*)</h1>').search(urllib2.urlopen('http://www.meituan.com/beijing').read()).groups()[0]
        return html

if __name__ == "__main__":
    app.run() 以FastCGI方式运行:
python code.py 9002 fcgi >/dev/null 2>&1 &

现在访问页面就可以看到抓取过来的今日团购信息了。

几个问题:
1.为什么听在9002上?
因为9000给了PHP,9001给了django。
2.">/dev/null 2>&1 &" 是什么意思?
用于把标准输出和错误输出全部直接丢弃。
3.如何更好的开发应用程序?
官方有文档,建议看官方的,本文主要是简单的介绍搭建方法。

附:简单写了个重启web.py的脚本,reboot_webpy.sh
#!/bin/sh
ps aux|grep 9002|grep -v "grep"|awk '{print $2}'|xargs kill
python /代码目录/code.py 9002 fcgi >/dev/null 2>&1 &

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/735e06ff8e77e97f1578d64cae5c2e68.html