使用 waitress 部署 Flask 服务,并且增加打印日志到文件

代码地址:

https://github.com/peiss/ant-learn-flask/tree/master/demo_deploy_flask

本部署框架的优点

  1. 单文件启动,python3 pss_waitress.py
  2. 入口文件可以多次启动,比如多次运行python3 pss_waitress.py,这样的好处是可以把python3 pss_waitress.py加到定时任务,每1分钟运行一次,那么如果进程挂掉了,就会自己启动起来了;
  3. 包含日志打印模块,打印到文件,并且会滚动删除

Flask 的代码

import logging
from flask import Flask

app = Flask(__name__)


@app.route('/')
def index():
  # 这样写日志
  logging.info("myendpoint We are computering now")
  return 'We are computering now'


@app.route('/server_status_code')
def server_status_code():
  """用于探活"""
  return "ok"


启动入口代码

import logging.handlers

LOG_FILE = "test_log.log"
log_format = "[%(levelname)s] %(asctime)s [%(filename)s:%(lineno)d, %(funcName)s] %(message)s"
logging.basicConfig(filename=LOG_FILE,
                    filemode="a",
                    format=log_format,
                    level=logging.INFO)
time_hdls = logging.handlers.TimedRotatingFileHandler(
  LOG_FILE, when='D', interval=1, backupCount=7)
logging.getLogger().addHandler(time_hdls)

logging.info("begin service")

import requests
from pss_app import app
from waitress import serve

DEPLOY_PORT = 8889


def process_is_alive():
  """检测本地进程是否存在"""
  try:
    r = requests.get(f"http://127.0.0.1:{DEPLOY_PORT}/server_status_code")
    if r.status_code == 200 and r.text == "ok":
      return True
    return False
  except Exception as e:
    return False


if __name__ == "__main__":
  logging.info("try check and start app, begin")
  if process_is_alive():
    logging.info("process_is_alive_noneed_begin")
  else:
    logging.info("process_is_not_alive_begin_new")
    serve(app, host='0.0.0.0', port=DEPLOY_PORT, threads=30)  # WAITRESS!

  logging.info("try check and start app, end")



安装依赖包

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple flask waitress requests

启动方式

python3 pss_waitress.py

代码截图

相关推荐