且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

自定义python数据库记录器,具有循环导入

更新时间:2023-02-16 17:53:14

我刚刚想出了另一种使用延迟导入来实现它的更规范的方法,我最初的问题是试图在 init 中导入模型strong>功能:

I just came up with another actually more canonical way of implementing it using delayed imports, my original problem was trying to import the model inside init function:

from logging import Handler

class DBHandler(Handler,object):
    model_name = None

    def __init__(self, model=""):
        super(DBHandler,self).__init__()
        self.model_name = model

    def emit(self,record):
        # instantiate the model
        try:
            model = self.get_model(self.model_name)
        except:
            from logger.models import GeneralLog as model

        log_entry = model(level=record.levelname, message=self.format(record))


        log_entry.save()

    def get_model(self, name):
        names = name.split('.')
        mod = __import__('.'.join(names[:-1]), fromlist=names[-1:])
        return getattr(mod, names[-1])