版权声明:内容版权为CSDN用户:kayseen 所有,若您需要引用、转载,需要注明来源及原文链接 https://blog.csdn.net/m0_43394876/article/details/88367650
1.环境配置及hello
1.安装nginx
- 安装
$ sudo apt-get install nginx
- 运行及停止
/etc/init.d/nginx start #启动
/etc/init.d/nginx stop #停止
- 配置文件
- 编辑文件:/etc/nginx/sites-available/default
# 如果是多台服务器的话,则在此配置,并修改 location 节点下面的 proxy_pass
upstream flask {
server 127.0.0.1:5000;
server 127.0.0.1:5001;
}
server {
# 监听80端口
listen 80 default_server;
listen [::]:80 default_server;
root /var/www/html;
index index.html index.htm index.nginx-debian.html;
server_name _;
location / {
# 请求转发到gunicorn服务器
proxy_pass http://127.0.0.1:5000;
# 请求转发到多个gunicorn服务器
# proxy_pass http://flask;
# 设置请求头,并将头信息传递给服务器端
proxy_set_header Host $host;
# 设置请求头,传递原始请求ip给 gunicorn 服务器
proxy_set_header X-Real-IP $remote_addr;
}
}
2.安装gunicorn
- 安装
pip install gunicorn
- 查看选项
gunicorn -h
- 运行
# -w: 表示进程(worker) -b:表示绑定ip地址和端口号(bind)
gunicorn -w 2 -b 127.0.0.1:5000 运行文件名称:Flask程序实例名
3.代码拷贝
- 拷贝本地代码到远程
scp -r 本地文件路径 [email protected]:远程保存路径
2.实例代码
1.hello.py
from flask import Flask
# 创建Flask的应用程序
# 第一个参数指代Flask所对应的模板,其可以决定静态文件从哪个位置开始找
app = Flask(__name__)
# 使用装饰器路由去与视图函数进行关联
@app.route('/')
def index():
return 'hello 2019'
if __name__ == '__main__':
# 运行当前Flask应用程序
app.run()
2.启动gunicorn
gunicorn -w 2 -b 127.0.0.1:5000 hello:app
启动之后显示如下:
(flask_hello) ubuntu@VM-0-5-ubuntu:~$ gunicorn -w 2 -b 127.0.0.1:5000 hello:app
[2019-03-09 16:06:10 +0800] [19417] [INFO] Starting gunicorn 19.9.0
[2019-03-09 16:06:10 +0800] [19417] [INFO] Listening at: http://127.0.0.1:5000 (19417)
[2019-03-09 16:06:10 +0800] [19417] [INFO] Using worker: sync
[2019-03-09 16:06:10 +0800] [19420] [INFO] Booting worker with pid: 19420
[2019-03-09 16:06:10 +0800] [19421] [INFO] Booting worker with pid: 19421
3.访问
此时打开你的公网ip就可以正常显示return的数据了,ok
下面来部署一个真实的flask项目
2.部署项目
1.先创建config.py文件里的数据库
注意指定数据库utf8
2.在manage.py同级目录下迁移数据
$ python manage.py db init
$ python manage.py db migrate -m"initial"
$ python manage.py db upgrade
3.登录数据库,source
4.启动nginx,gunicorn
/etc/init.d/nginx stop #停止
/etc/init.d/nginx start #启动
gunicorn -w 2 -b 127.0.0.1:5000 manage:app