flask带日志的微服务封装

flask的具体实例用法

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
# @Time    : 2020-05-18 16:11:10
# @Author  : Bakuya Liu
# @File    : getCourtInformation_flask.py

Description:

"""
from flask import Flask, render_template, request, Response, jsonify
from flask_cors import CORS
from flask import request
import datetime
import time
import pytz
import os
import sys
import json
sys.path.append("/home/release/court_nlp_release/courtInformationExtractor")
from service.getInfoCombination import getCombination
import logging
from logging.handlers import RotatingFileHandler
import warnings


warnings.filterwarnings("ignore")
app = Flask(__name__)
CORS(app, supports_credentials=True)

@app.before_request
def before_request():
    # import face_interface
    ip = request.remote_addr
    url = request.url
    app.logger.info('ip: %s, url: %s user is accessing!', ip, url)

@app.route('/CourtInformation',methods=["get"])
def getCourtInformation():
    try:
        data = json.loads(request.get_data())
        print("1")
        result = getCombination(data)
        file = "./log_CourtInformation.txt"
        # 鍒ゆ柇鏂囦欢鏄惁瀛樺湪锛屼笉瀛樺湪鍒欏垱寤?
        if not os.path.exists(file):
            os.mknod(file)
        with open(r'./log_CourtInformation.txt', 'a+') as f_log:
            now_time = datetime.datetime.fromtimestamp(int(time.time()), pytz.timezone('Asia/Shanghai')).strftime('%Y-%m-%d %H:%M:%S')
            data = now_time + ',' + 'getCourtInformation' + ',' + 'running success.\n'
            f_log.writelines(data)
        app.logger.info('The algorithm called successfully!')
        return jsonify(result)
    except Exception as e:
        logging.exception(e)
        raise

# 鍙戦€佺姸鎬?
@app.route('/heartbeat', methods=['POST'])
def heartbeat():
    try:
        PID = os.getpid()
        with open('./data.json', encoding='utf-8', errors='ignore') as f:
            data = json.load(f)
        result = getCombination(data)
        if len(result) != 0:
            algorithm_status = 'running'
        else:
            algorithm_status = 'stopped'

        if not os.path.exists('./log_CourtInformation.txt'):
            return "The algorithm has not been called!"
        with open('./log_CourtInformation.txt', 'r') as f:
            lines = f.readlines()
            last_line = lines[-1].split(',')
            last_call_time = last_line[0]
            name = last_line[1]
            call_count = len(lines)

        response = {
            "response_getCourtInformation":{
                'name': name,
                'status': algorithm_status,
                'call_count': call_count,
                'last_call_time': last_call_time,
                'pid': PID
            }
        }
        return jsonify(response)
    except Exception as e:
        logging.exception(e)
        return ''


if __name__ == '__main__':
    # 鐢熸垚鏃ュ織鏂囦欢
    app.debug = True
    logging.basicConfig(level=logging.DEBUG)
    formatter = logging.Formatter(
        "[%(asctime)s][%(filename)s:%(lineno)d][%(levelname)s][%(thread)d] - %(message)s")
    handler = RotatingFileHandler("flask.log", maxBytes=102400, backupCount=10)
    logging.getLogger().addHandler(handler)
    handler.setFormatter(formatter)
    app.run(host='0.0.0.0', port=5000, debug=True)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值