阿里云centOS7部署flask,python3

用的是阿里云镜像市场的CentOS7镜像,已经安装好python3和mysql了。通常途径是,安装flask,测试python3,配置gunicorn,配置Nginx。工具用的是XShell6,XFtp6.

1.安装flask,采用pip安装:pip install flask 或者pip3 install flask

2.将本地flask工程代码,上传至目标文件夹,例如我的是在www文件中,就将本地工程拖进来即可,文件名flaskTest.py测试的flask代码如下:

from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
    return '<h1>Hello World!This is a ...</h1>'
if __name__ == '__main__':
    app.run()

 3.安装gunicorn:pip3 install gunicorn

4.安装nginx,并配置。pip install nginx,并修改配置,我的配置文件在/etc/nginx/nginx.conf,里面需要修改的部分如下:

server {
        listen       80;
        server_name     配置域名或者公网ip地址;
        # Load configuration files for the default server block.
        location / {
proxy_pass http://127.0.0.1:8000; #本地8000端口最终指向域名地址
                proxy_set_header Host $host;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

修改后,可以通过nginx -t 测试配置文件是否正确。

要注意将修改的端口开放。

5.通过命令:ps -ef|grep gunicorn 可以明确当前gunicorn是否运行(并看到进程号)。进入www文件夹:cd /www,并用命令gunicorn flaskTest:app ,启动服务。kill -9 进程号,杀掉当前进程。

6.涉及一个问题:每一次服务器重启的时候,都要敲一遍下面的代码:

service nginx start
cd /www
gunicorn flaskTest:app

这样才能正常启动服务。但是Linux下可以写sh脚本,比如我在www文件夹下新建一个flaskService.sh的脚本,里面写下列代码:

#!/bin/bash
service nginx start
cd /
gunicorn www.flaskTest:app

再在终端cd /www,写 sh flaskService.sh 这个命令,也能如上面一样启动。那么如何设置为开机启动服务呢,在etc文件夹中,有文件rc.local,代码如下:

#!/bin/bash
# THIS FILE IS ADDED FOR COMPATIBILITY PURPOSES
#
# It is highly advisable to create own systemd services or udev rules
# to run scripts during boot instead of using this file.
#
# In contrast to previous versions due to parallel execution during boot
# this script will NOT be run after all other services.
#
# Please note that you must run 'chmod +x /etc/rc.d/rc.local' to ensure
# that this script will be executed during boot.

touch /var/lock/subsys/local
cd /www
sh ./flaskService.sh

最后两行,就是开机启动的服务,首先进入www文件夹,再执行这个脚本。


接下来,就是微信小程序操作数据库,以及python中自己来写api,并在微信小程序中调用了。

猜你喜欢

转载自blog.csdn.net/limaning/article/details/82343364