美文网首页
flask接口目录结构设计以及log模块初始化分享

flask接口目录结构设计以及log模块初始化分享

作者: 繁华丶凋零 | 来源:发表于2022-08-12 10:26 被阅读0次

    目录结构

    codebeamer-manage
    ├── bin
    │   ├── start.sh
    │   └── stop.sh
    ├── conf
    │   └── conf.ini
    ├── data
    ├── logs
    │   ├── bugsync.log
    └── project
        ├── codebeamer_api.py
        ├── codebeamer_manager.py
    
    

    1.codebeamer-manage/bin/start.sh

    工程启动脚本

    #!/bin/sh
    basepath=$(cd `dirname $0`; pwd)
    echo $basepath
    nohup python3 $basepath/../project/codebeamer_api.py 2>&1 /dev/null &
    

    2.codebeamer-manage/bin/stop.sh

    工程停止脚本

    #!/bin/bash
    name='codebeamer_api.py'
    pid=$(ps -ef|grep "../project/$name"|grep -v grep|awk '{print $2}')
    if [ -z "$pid" ];then
        echo 'process is not alived'
    else
        echo 'kill process'
        kill -9 $pid
        pid=$(ps -ef|grep "../project/$name"|grep -v grep|awk '{print $2}')
        if [ -z "$pid" ];then
            echo 'kill process success'
        else
            echo 'kill process error'
        fi
    fi
    

    3.codebeamer-manage/conf/conf.ini

    工程配置文件
    conf.ini里内容自行替换成 正确配置

    [log]
    loglevel = debug
    logname = bugsync.log
    interval = 1
    backupCount = 7
    when = MIDNIGHT
    encoding = utf-8
    
    
    [mongodb]
    host = 1.2.3.4
    dbname = dbname
    user = user
    password = password
    
    
    [codebeamer]
    url = codebeamer_url
    Authorization = codebeamer_key
    
    [bugzilla]
    url = bugzilla_url
    key = bugzilla_key
    

    4.codebeamer-manage/project/codebeamer_api.py

    工程接口文件

    from flask import Flask, render_template, request, redirect, url_for
    from flask_cors import CORS
    import json
    import codebeamer_manager
    
    app = Flask(__name__)
    CB = codebeamer_manager.Manager(codebeamer_manager.CONF_PATH)
    
    
    @app.route('/api/codebeamer/item',methods=['POST', 'GET'])
    def item_create():
        if request.method == 'POST':
            bugid = request.json['bugid']
            project = request.json['project']
            tracker = request.json['tracker']
            result = {bugid':bugid ,'project':project,'tracker':tracker }
            return(json.dumps(result))
    
    
    if __name__ == '__main__':
        CORS(app, supports_credentials=True)
        app.run(host='0.0.0.0', port="50001",debug=True)
    

    5.codebeamer-manage/project/codebeamer_manager.py

    工程主功能函数文件

    # -*- coding: UTF-8 -*-
    
    import os
    import sys
    import time
    import logging
    import configparser
    import re
    from logging.handlers import TimedRotatingFileHandler
    import json
    import pymongo
    from pymongo import MongoClient
    import bugzilla
    import codebeamer
    import requests
    
    
    
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    CONF_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),'conf','conf.ini')
    
    
    def getNowTime():
        return time.strftime(r'%Y%m%d%H%M%S',time.localtime(time.time()))
    
    
    class param():
        def __init__(self,confPath):
            self.conf = configparser.ConfigParser()
            self.conf.read(confPath)
            self.mongodb_init()
            self.log_init()
            self.codebeamer_init()
            self.bugzilla_init()
    
        def mongodb_init(self):
            self.mongodb = {}
            self.mongodb['host'] = self.conf.get('mongodb','host').split(',')
            self.mongodb['dbname'] = self.conf.get('mongodb','dbname')
            self.mongodb['user'] = self.conf.get('mongodb','user')
            self.mongodb['password'] = self.conf.get('mongodb','password')
    
        def log_init(self):
            self.log = {}
            self.log['loglevel'] = self.conf.get('log','loglevel')
            self.log['logname'] = self.conf.get('log','logname')
            self.log['interval'] = self.conf.getint('log','interval')
            self.log['backupCount'] = self.conf.getint('log','backupCount')
            self.log['when'] = self.conf.get('log','when')
            self.log['encoding'] = self.conf.get('log','encoding')
    
        def codebeamer_init(self):
            self.codebeamer = {}
            self.codebeamer['url'] = self.conf.get('codebeamer','url')
            self.codebeamer['Authorization'] = self.conf.get('codebeamer','Authorization')
    
        def bugzilla_init(self):
            self.bugzilla = {}
            self.bugzilla['url'] = self.conf.get('bugzilla','url')
            self.bugzilla['key'] = self.conf.get('bugzilla','key')
    
    class Manager():
        def __init__(self,conf_path):
            self.param = param(conf_path)
            # log
            self.param.log['logname'] = os.path.join(BASE_DIR,'logs',self.param.log['logname'])
            self.logger_init(**self.param.log)
            # mongo client
            self.mongodb_init(**self.param.mongodb)
            self.codebeamer_init(**self.param.codebeamer)
            self.bugzilla_init(**self.param.bugzilla)
    
        # 初始化部分-------
        def logger_init(self,loglevel,logname,interval,backupCount,when,encoding):
            logger = logging.getLogger('log')
            logger.setLevel(logging.DEBUG)
    
            # 移除掉所有的handler
            while logger.hasHandlers():
                for i in logger.handlers:
                    logger.removeHandler(i)
    
            # file log
            formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
            fh = TimedRotatingFileHandler(logname, when=when, interval=interval, backupCount=backupCount,encoding=encoding)
            fh.setLevel(logging.DEBUG)
            fh.setFormatter(formatter)
            logger.addHandler(fh)
    
            # console log
            self.logger = logger
    
        def mongodb_init(self,host,dbname,user,password):
            self.logger.debug("begin init mongodb connection")
            try:
                self.client = pymongo.MongoClient(host)
                self.db = self.client[dbname]
                self.db.authenticate(user,password)
            except Exception as e:
                self.logger.error("Failed to connect to MongoDB!")
                self.logger.error(str(e))
                raise e
            self.logger.debug("connect to MongoDB success!")
    
    
        def codebeamer_init(self,url,Authorization):
            self.logger.debug("begin init codebeamer connection")
            try:
                self.cli_cb = codebeamer.Codebeamer(url,Authorization)
            except Exception as e:
                self.logger.error("Failed to connect to codebeamer!")
                self.logger.error(str(e))
                raise e
            self.logger.debug("connect to codebeamer success!")
    
    
        def bugzilla_init(self,url,key):
            self.logger.debug("begin init bugzilla connection")
            try:
                self.cli_bg = bugzilla.Bugzilla(url,key)
            except Exception as e:
                self.logger.error("Failed to connect to bugzilla!")
                self.logger.error(str(e))
                raise e
            self.logger.debug("connect to bugzilla success!")
    
    

    相关文章

      网友评论

          本文标题:flask接口目录结构设计以及log模块初始化分享

          本文链接:https://www.haomeiwen.com/subject/fjyxgrtx.html