前言
概念理解
需要的材料
什么是nginx?
什么是flup/WSGI?
- from wsgiref.simple_server import make_server
-
- def hello_world_app(environ, start_response):
- status = '200 OK' # HTTP Status
- headers = [('Content-type', 'text/plain')] # HTTP Headers
- start_response(status, headers)
-
- # The returned object is going to be printed
- return ["Hello World"]
-
- httpd = make_server('', 8000, hello_world_app)
- print "Serving on port 8000..."
-
- # Serve until process is killed
- httpd.serve_forever()
这段代码解释了
WSGI协议中python满足什么样的代码可以 在服务器中运行 。
可以在服务器中运行的是一个方法 。 方法第一个参数其实就是一个字典对象,里面是所有从用户请求和服务器环境变量中获取的信息内容,协议当然会定义一些必须有的值,及这些值对应的变量名;第二个参数其实就是一个回调函数,它向应用端传递一个用来生成响应内容体的write对象,这个对象也是有__call__方法的。
协议也提到了,还可以设计中间件来连接服务器端与应用端,来实现一些通用的功能,比如session、routing等。
什么是flask?
j2ee中有一个框架叫struts 。 flask就是python中的struts!
实践 :
首先下载nginx
1)下载地址:
http://nginx.org
2)启动
解压至c:\nginx,运行nginx.exe(即nginx -c conf\nginx.conf),默认使用80端口,日志见文件夹C:\nginx\logs
3)使用
http://localhost
配置nginx,找到nginx.conf
添加一段如下代码
server
{
listen 8000;
server_name test.com;
location /
{
#fastcgi_pass unix:/tmp/python-cgi.sock;(注1)
fastcgi_pass 127.0.0.1:8008; (注意这里的端口和上面的listen的8000端口要不一样,否则会报地址已占用的错)
fastcgi_param SCRIPT_FILENAME "";
fastcgi_param PATH_INFO $fastcgi_script_name;
include fcgi.conf;
}
}
下载flup
到命令行输入 pip.exe install flup . 就可以安装flup了 。
然后我们再写一个fcgi.py,代码如下
#!/usr/bin/python
# encoding : utf-8
from flup.server.fcgi import WSGIServer
def myapp(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/plain')])
return ['Hello World!\n']
if __name__ == '__main__':
WSGIServer(myapp,bindAddress=('127.0.0.1',8008)).run()(注2)
运行到这了,我们就可以在浏览器里面敲: http://localhost:8000
如果返回 Hello World,恭喜你,迈出了nginx 运行python的第一步
参考的文章有
http://blog.163.com/sky20081816@126/blog/static/16476102320108254032278/ 捉摸Python的WSGI(转)