FlaskDemo 命名为test.py
# coding=utf-8 from flask import Flask app = Flask(__name__) @app.route("/") def index(): return "test" if __name__ == '__main__': app.debug = True # 这里host一定要写0.0.0.0 写127.0.0.1的无法访问 ——_—— app.run(host="0.0.0.0", port=5000)
服务器配置
# 必须安装的包 pip install flask pip install gunicorn
直接运行
python test.py runserver
gunicorn运行 推荐!!!
#直接运行,默认启动的127.0.0.1::8000 gunicorn 运行文件名称:Flask程序实例名 #指定端口 gunicorn -w 4 -b HOST:端口 运行文件名称:Flask程序实例名 #-w 表示进程(worker)。 #-b 表示绑定ip地址和端口号(bind) # test 运行的文件名称对应 test.py # app Flask程序实例名对应 app = Flask(__name__) 如: #直接运行 gunicorn -w 4 -b 0.0.0.0:5000 test:app #后台运行 gunicorn -w 4 -b 127.0.0.1:5000 test:app --daemon
更好的启动方式
添加配置文件gunicorn.conf
# 并行工作线程数 workers = 4 # 监听内网端口5000【按需要更改】 bind = '0.0.0.0:5000' # 设置守护进程【关闭连接时,程序仍在运行】 daemon = True # 设置超时时间120s,默认为30s。按自己的需求进行设置 timeout = 120 # 设置访问日志和错误信息日志路径 # accesslog = './logs/acess.log' # errorlog = './logs/error.log'
运行程序
# gunicorn 运行模块名:应用名 -c 配置文件 gunicorn service:app -c gunicorn.conf
如果你想尝试使用其他py版本运行
1.查看gunicorn位置
which gunicorn
2.打开文件并编辑第一行指定版本
#!/usr/bin/python3.7 # -*- coding: utf-8 -*- import re import sys from gunicorn.app.wsgiapp import run if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script.pyw?|.exe)?$', '', sys.argv[0]) sys.exit(run())
3.运行
gunicorn server:app -c gunicorn.conf
ps:
如果运行出现一下警告,尝试将文件gunicorn.conf更改为 gunicorn.py在运行
!!!
!!! WARNING: configuration file should have a valid Python extension.
!!!