CMDB02/单例模式、资产采集参考命令、日志处理
昨日内容回顾
restful规范?
什么是jwt?
drf都集成过哪些视图类?
drf认证的流程?drf认证和django中间件的关系?【组长组织组员】
为什么开发cmdb?
cmdb是如何实现的?
cmdb资产采集后,为什么不直接放到数据库?
- 单独编写api,为了给其他系统提供数据支持(接口)
- 维护的数据库连接比较多,修改不方便。
今日详细
1. 单例模式
1.2 “多例模式”
class Foo(object):
def __init__(self,name,age):
self.name = name
self.age = age
def func(self):
msg = "%s-%s" %(self.name,self.age)
obj1 = Foo("常鑫",18) # Foo的一个对象/Foo类的一个实例
obj1.func()
obj2 = Foo("李业",19)
obj2.func()
1.3 单例模式
class Foo(object):
instance = None
def __init__(self,name,age):
self.name = name
self.age = age
def __new__(cls,*arg,**kawrgs):
if not cls.instance:
cls.instance = object.__new__(cls)
return cls.instance
class Singleton(object):
instance = None
def __init__(self):
self.name = None
def __new__(cls, *arg, **kawrgs):
if not cls.instance:
cls.instance = object.__new__(cls)
return cls.instance
应用场景:
django配置文件,只要加载一次,以后使用都用同一份值。
class Singleton(object): instance = None def __init__(self): self.k0 = 0 self.k1 = 1 self.k2 = 2 ... def __new__(cls, *arg, **kawrgs): if not cls.instance: cls.instance = object.__new__(cls) return cls.instance obj1 = Singleton() obj2 = Singleton() obj3 = Singleton()
django的admin,在注册models中用,希望所有的model类注册到同一个列表中。
1.3.1 单例模式是错误
class Singleton(object):
instance = None
def __init__(self):
self.name = None
def __new__(cls, *arg, **kawrgs):
if not cls.instance:
cls.instance = object.__new__(cls)
return cls.instance
1.3.1 单利模式 new(正确)
import time
import threading
class Singleton(object):
instance = None
lock = threading.RLock()
def __new__(cls, *arg, **kwargs):
if cls.instance:
return cls.instance
with cls.lock:
if not cls.instance:
cls.instance = object.__new__(cls)
return cls.instance
obj1 = Singleton()
obj2 = Singleton()
1.3.2 文件导入(正确),在源码中的应用
# xx.py
class Site(object):
def __init__(self):
self.names = []
def xx(self):
pass
site = Site()
import xx
print(xx.site)
实例
# xx.py class Singleton(object): def __init__(self): self._registry = [] def register(self,model_class): self._registry.append(model_class) site = Singleton()
import xx xx.site
总结
基于
__new__
实现单例模式import time import threading class Singleton(object): instance = None lock = threading.RLock() def __new__(cls, *arg, **kwargs): if cls.instance: return cls.instance with cls.lock: if not cls.instance: cls.instance = object.__new__(cls) return cls.instance obj = Singleton() print(obj)
基于文件导入实现单利模式
# sg.py class Singleton(object): pass obj = Singleton()
import sg print(sg.obj)
应用场景:
- django中settings配置文件
- django的admin内部使用,将所有model类注册到了一个字典中。
疑问
基于__new__
实现单利模式,在init中不设置值。
是单利,但数据会被覆盖
class Singleton(object): instance = None def __init__(self): self.registry = [] def __new__(cls, *arg, **kawrgs): if not cls.instance: cls.instance = object.__new__(cls) return cls.instance def register(self, val): self.registry.append(val) # {registry:[]} obj1 = Singleton() # {registry:[x1]} obj1.register('x1') # instance = {registry:[x1]} # instance = {registry:[]} obj2 = Singleton() # instance = {registry:[x2]} obj2.register('x2') print(obj2.registry) print(obj1.registry)
单例模式
class Singleton(object): instance = None registry = [] def __new__(cls, *arg, **kawrgs): if not cls.instance: cls.instance = object.__new__(cls) return cls.instance def register(self, val): self.registry.append(val) obj1 = Singleton() obj1.register('x1') obj2 = Singleton() obj2.register('x2') print(obj2.registry) print(obj1.registry)
面试题
- 手写单利模式(new+锁)?
- 其他单例模式?
__new__
方法返回的是什么? 新创建的对象,内部没有数据,需要经过init来进行初始化。- 单利模式应用场景:
- django的配置文件
- django的admin
- 数据库链接池(单利模式)
- 写日志
2. 获取日志堆栈信息
import traceback
def run():
try:
int('asdf')
except Exception as e:
print(traceback.format_exc())
if __name__ == '__main__':
run()
3. 获取资产的命令
内存信息
sudo dmidecode -q -t 17 2>/dev/null 注意:linux上要提前安装 yum install dmidecode
硬盘(安装MegaCli)
sudo MegaCli -PDList -aALL
网卡
sudo ip link show sudo ip addr show
主板
sudo dmidecode -t1
CPU
cat /proc/cpuinfo
4.数据封装
class BaseResponse(object):
def __init__(self):
self.status = True
self.data = None
self.error = None
@property
def dict(self):
return self.__dict__
def process():
info = BaseResponse()
try:
info.status = True
info.data = "sfdsdf"
except Exception:
pass
return info.dict
result = process()
print(result)
作业:将课上代码换成BaseResponse方式。
5.表关系
作业
在中控机中应用BaseResponse
在api中创建表结构
汇报资产数据,数据录入数据库
models.Disk.objects.create(pdtype='xx',capacity='x') models.Disk.objects.create(**{}) models.Disk.objects.bulk_create([])
资产变更记录【可选】
集合:交并差