Flask配置方法

flask应用的配置(使用uWSGI和Nginx在CentOS 7上搭建)

基础的Nginx 数据库等配置省略

创建python虚拟环境

sudo pip install virtualenv
mkdir ~/myproject
cd ~/myproject
virtualenv myprojectenv
source myprojectenv/bin/activate

安装 Flask 和 uWSGI

pip install uwsgi flask

创建一个小应用

vi ~/myproject/myproject.py
from flask import Flask
application = Flask(__name__)

@application.route("/")
def hello():
    return "<h1 style='color:blue'>Hello There!</h1>"

if __name__ == "__main__":
    application.run(host='0.0.0.0')

运行

python myproject.py

浏览器打开服务器5000端口,看到蓝色的Hello There!就表示成功了。

创建 WSGI 入口

vi ~/myproject/wsgi.py
from myproject import application

if __name__ == "__main__":
    application.run()

运行

uwsgi --socket 0.0.0.0:8000 --protocol=http -w wsgi

浏览器打开服务器8000端口,看到蓝色的Hello There!就表示成功了。

创建uWSGI Configuration文件

vi ~/myproject/myproject.ini
[uwsgi]
module = wsgi

master = true
processes = 5

socket = myproject.sock
chmod-socket = 660
vacuum = true

die-on-term = true

创建Systemd Unit文件

sudo vi /etc/systemd/system/myproject.service
[Unit]
Description=uWSGI instance to serve myproject
After=network.target

[Service]
User=user
Group=nginx
WorkingDirectory=/home/user/myproject
Environment="PATH=/home/user/myproject/myprojectenv/bin"
ExecStart=/home/user/myproject/myprojectenv/bin/uwsgi --ini myproject.ini

[Install]
WantedBy=multi-user.target

这样就能用systemd命令控制我们的小应用了

sudo systemctl start myproject
sudo systemctl enable myproject

配置nginx

sudo nano /etc/nginx/nginx.conf

server {}上方添加一个server {}脚本

http {
    . . .

    include /etc/nginx/conf.d/*.conf;

    server {
    }

    server {
        listen 80 default_server;

        . . .
server {
    listen 80;
    server_name server_domain_or_IP;

    location / {
        include uwsgi_params;
        uwsgi_pass unix:/home/user/myproject/myproject.sock;
    }
}

将nginx user加入你的user group

sudo usermod -a -G user nginx

配置group的权限

chmod 710 /home/user

看看nginx配置文件有没有语法错误

sudo nginx -t

之后启动

sudo systemctl start nginx
sudo systemctl enable nginx

这样就能在80端口访问我们的小应用了!

posted @ 2018-07-03 18:38  软件工程第六组  阅读(186)  评论(0编辑  收藏  举报