centos 7 nginx+uwsgi+flask 环境搭建

来源:互联网 发布:清水建设 知乎 编辑:程序博客网 时间:2024/05/21 09:46

1 安装准备

1.1 下载安装python2.7 flask-0.11.1 nginx-1.6.3 uwsgi-2.0.13.1

  • sudo yum install python-flask
  • sudo yum install nginx
  • sudo yum install uwsgi

1.1.1 测试flask

  • 新建文件test_flask.py
    from flask import Flaskapp = Flask(__name__)@app.route("/")def hello():    return "Hello World!"if __name__ == "__main__":    app.run()
  • 运行文件 python test_flask.py
  • 在浏览器中输入localhost:5000 观察到hello world 表示配置成功

1.1.2 测试uwsgi

  1. 编写测试脚本test.py
    #!/usr/bin/pythondef application(env, start-response):    start-reponse('200 OK','[('Content_Type','text/html')]')    return "Congraduations!!"
  2. 启动web server uwsgi –http :9090 –wsgi-file test.py
    • 出现错误 unrecognize option : –wsgi-file
      • 问题解决方案 uwsgi 版本太旧造成的,通过pip 安装uWSGI就可以了
  3. 访问localhost:9090

1.1.3 测试nginx

直接在浏览器中输入localhost:80中看到欢迎页面表示环境安装成功

2 文件配置

2.1 编写测试文件

新建文件test.py

from flask import Flaskapp = Flask(__name__)@app.route("/")def hello():    return "Hello World!"if __name__ == "__main__":    app.run()

2.2 为uwsgi配置Nginx

在nginx的conf.d的目录下创建一个test.conf文件

  • server{
  • listen 8000;
  • server_name localhost;
  • #此root路径是指要运行的python存放的目录,也就是项目工程的目录
  • root /usr/share/nginx/html;
  • location /{
  • include uwsgi_params;
  • uwsgi_pass 127.0.0.1:8001;#此端口数值要记下
  • }
  • error_page 500 502 503 504 /50x.html;
  • location = /50x.html{
  • root html;#相对路径
  • }

-}

2.3 为Flask Web项目添加uWSGI配置文件

2.3.1 在上面提到的项目工程目录中,新建test_conf.xml(test 是测试python的文件名,最好是工程名字,便于维护)

  • <uwsgi><br/>
  • <socket>:8001</socket><br/>
  • <callable>app</callable>#test.py 中对象的名字<br/>
  • <wsgi-file>test.py</wsgi-file><br/>
  • <module>test</module><br/>
  • <process>4</process><br/>
  • </uwsgi><br/>

2.3.2 启动uwsgi

uwsig -x test_conf.xml

2.3.3 在浏览器中输入localhost:8000

若有欢迎信息,表示配置正确

3 学习资源

  • http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
  • http://www.pythondoc.com/flask-mega-tutorial/ 中文版
  • http://flask.pocoo.org/docs/0.11/ 官方文档
0 0