Nginx+uWSGI 入门

Nginx+uWSGI 入门

开始

  • 确保一下软件包安装被安装上:html

    <pre> ubuntu: #apt-get install uwsgi-plugin-python nginx </pre>前端

简要介绍一下:python

  1. nginx 是一个 http 服务器,与 apache、lighttpd、Microsoft IIS 等属于同类产品;
  2. uwsgi 是 http 服务器 与 python 应用程序之间进行数据交换的服务程序;

出错试验

从一个 uwsgi 出错试验开始:nginx

  • 建立 hello.py

    <pre> def application(env, start_response): start_response('200 OK', [('Content-Type','text/html')]) return ["Hello World"] </pre>web

  • 开启一个uwsgi 守护进程

    <pre> /usr/bin/uwsgi_python -s 127.0.0.1:9090 --file hello.py --daemonize uwsgi.log </pre>apache

如今,打开网络浏览器,在地址栏中输入”http://127.0.0.1:8000“并回车,这时网页中会显示“The connection was reset……"当你不断刷新浏览器,日志文件 uwsgi.log 中应当能够看到相似下面的信息ubuntu

  • 出错信息

    <pre> invalid request block size: 21573 (max 4096)...skip Thu Feb 20 03:29:28 2014 - error parsing request invalid request block size: 21573 (max 4096)...skip Thu Feb 20 03:29:28 2014 - error parsing request invalid request block size: 21573 (max 4096)...skip Thu Feb 20 03:29:29 2014 - error parsing request ... </pre>后端

这表示,你在浏览器中提交的 http 请求被 uwsgi 给忽视了。若是你不断的刷新那个页面,终端中会不断涌出该信息。虽然咱们获得的是被重置的页面,可是这足以证实 uwsgi 是一个 http 服务器。继续在/etc/nginx/sites-available/default 中添加以下配置:浏览器

  • nginx-cgi 配置服务器

    <pre> server { listen 80; server_name 127.0.0.1; location /cgi { include uwsgi_params; uwsgi_pass 127.0.0.1:8000; } } </pre>

  • 重启服务 /etc/init.d/nginx restart

重启nginx服务后,使用浏览器打开: 127.0.0.1/cgi 终于如愿出现久违的 Hello World ,而不是“The connection was reset..."

小结

uwsgi 实际上也是一个 http 服务器,只不过它只面向 python 网络应用程序。虽然 uwsgi 也是 http 服务器,可是却不能直接使用它部署 python web 应用程序,不然会出错。

在本文中,uwsgi 所扮演的的角色是后端 http 服务器,nginx 扮演的角色是前端 http 服务器,hello.py 是客户端应用程序。 用户从网页浏览器中发出请求,nginx 服务器收到请求后,会经过它的 uwsgi 模块将用户的请求转发给 uwsgi 服务器,uwsgi 服务器处理完毕后将结果返回给 nginx,浏览器将最终的结果展示给用户。

参考

相关文章
相关标签/搜索