Package: simutil
SimUtilpython容器& libs1. 安装pip install simutil2. 添加配置文件你需要在你的项目根目录下创建一个.env文件，内容如下:[environment]# 环境变量 环境变量的配置一定要放在[environment]下, 否则读取不到ENVIRONMENT=dev# 项目环境#日志配置# LOG_DEBUG:日志调试模式LOG_DEBUG=true# LOG_LEVEL:DEBUG|LOG_LEVEL=DEBUG# 日志路径: 每天产生一个新文件# 日志具体文件名: 一直记录到该文件中LOG_PATH=/Users/**/# redis配置REDIS_HOST=127.0.0.1REDIS_PORT=6379REDIS_PASSWORD=REDIS_DB=0# rabbitmq 配置RABBITMQ_HOST=127.0.0.1RABBITMQ_PORT=5672RABBITMQ_USER=testRABBITMQ_PASSWORD=12345# oss配置OSS_ACCESS_DOMAIN=**OSS_ACCESS_KEY=keyOSS_ACCESS_SECRET=secretOSS_BUCKET_NAME=bucket_nameOSS_END_POINT=endpoint[default.mysql]# 数据库等其他配置DB_TYPE=mysqlDB_HOST=127.0.0.1DB_PORT=3306DB_NAME=devDB_USER=rootDB_PASSWORD=passwordDB_CHARSET=utf8mb43. 初始化容器BASE_PATH注册fromsimutil.Appimportappimportosbase_path=os.path.dirname(os.path.dirname(__file__))app.register("BASE_PATH",os.path.dirname(os.path.dirname(__file__)))# 注册完成之后, 你可以在代码任何地方引入app并使用读取env配置app('env')('LOG_PATH')# 方法式读取app('env')('LOG_PATH1',"hahaha")# 方法式读取(娶不到舍默认值）app('env').LOG_PATH# 属性读取app('env')['LOG_PATH']# 字典读取app('env').items('default.mysql')# 模块读取app('env').items('sqlserver','DB_HOST')# 读取default.mysql中的DB_HOSTapp('env').items('sqlserver','DB_HOST1',"123")# 读取default.mysql中的DB_HOST(带默认值)log日志app('log').debug(("status",0))# 记录tupleapp('log').info([1,2,3,4,5])# 记录listapp('log').error({'name':'jemes'})# 记录dictapp('log').warning("123444")# 记录stringapp('log').critical(5)# 记录numbertry:a=100/0# errorraiseException("i am a Exception")# ExceptionexceptExceptionase:app('log').info(e)# 记录error or exception网络请求request# 同步request getrep=app('request').get('https://api.longhash.com/',params={},header={})text=rep.textjson=rep.json()# 同步request postrep=app('request').post('https://api.longhash.com',params={},header={})text=rep.textjson=rep.json()# 异步request getasyncdeftest(url,param={}):res=awaitapp('request').aiogett(url,param)text=res.textjson=res.json()app('async').run([test('https://api.longhash.com/')])# 异步方法调用# 异步request postasyncdeftest(url,param={}):res=awaitapp('request').aiopost(url,param)text=res.textjson=res.json()app('async').run([test('https://api.longhash.com/')])# 异步方法调用读取项目中配置文件信息# config 读取app 注册的BASE_PATH下文件配置app('config')('Config.setting.test_str')# {BASE_PATH}/Config/setting.py test_str值app('config')('Config.setting.test_str','default')# {BASE_PATH}/Config/setting.py test_str值 取不到则用默认值defaultapp('config').get('Config.setting.test_str','default')# {BASE_PATH}/Config/setting.py test_str值 字典方式读取redis# redisapp('redis').set('name',123)# 设置keyapp('redis').get('name')# 读取keyapp('redis').select(1).get('name')# 切换redis DB: 1# 如果想使用其他非 .env中的配置的redis， 建议使用app.register 注册新的redis实例fromsimutil.RedisimportRedisredis=Redis(app('env').REDIS_HOST,app('env').REDIS_PORT)app.register('redis1',redis)app('redis1').get('testname')async方法# 异步方法importasyncioasyncdefhello(index):# 自定义的async方法print("number:{}, Hello world!".format(index))awaitasyncio.sleep(1)print("end!")app('async').run([hello(index)forindexinrange(5)])# 执行阿里OSS# ossrep=app('request').get('https://api.***.com/index',params={},header={})# 上传读取的内容(从内存中)app('oss').push('oss/api.json',rep.text)# oss/api.json为上传到oss的文件路径名称# 设置refererapp('oss').referer(["http://api.longhash.com"]).push('test/api.json',rep.text,{'Content-Encoding':'utf-8'})# 取消referer 或设置为空app('oss').referer().push('test/api.json',rep.text,{'Content-Encoding':'utf-8'})# 上传本地文件filepath=/Users/jemes/workspace/simutil/Storage/Logs/20200528.logapp('oss').push_file('test/api.json',filepath,{'Content-Encoding':'utf-8'})# rule规则设置app('oss').rule(allowed_origins=['*'],allowed_methods=['GET'],allowed_headers=['*'],max_age_seconds=100)\.push_file('test/api.json','/Users/jemes/workspace/simutil/Storage/Logs/20200528.log')Path路径rep=app('path')# 指向BASE_PATH的Pathlib对象base_path=app('path').resolve()# = app('BASE_PATH')config_path=rep.joinpath('Config')# {BASE_PATH}/Configlogs_path=rep.joinpath('Storage/Logs')# {BASE_PATH}/Storage/Logs# 其他操作和Pathlib一致rabbitMQrab=app('rabbitmq')# 指向BASE_PATH的Pathlib对象conn=rab.connection()# rabbitmq connectionchannel=rab.channel()# rabbitmq channelApp容器# 为了实现代码结偶和复用, 延时加载# 说明: app('keyname') 拿出来的都是单例, App本身也是单例模式# 注册classclassDemoA:defhello(self):return'DemoA say hello'demo1=app.register('demo1',DemoA)# 类名注册demo2=app.register('demo2','__main__.DemoA')# 类路径注册(我在main函数中执行的，所以路径为__main__.DemoA)demo3=app.register('demo',DemoA())# 实例注册res=app('demo1').hello()# print: DemoA say hellores=app('demo2').hello()# print: DemoA say hellores=app('demo3').hello()# print: DemoA say hello# 注册functiondefadd(a,b):returna+bapp.register('add',add)# 方法注册res=app('add')(4,5)# print: 9# 注册数据app.register('listdata',[1,3,22,21,39])app.register('dictdata',{'name':'jemes'})app.register('tupledata',('name','jemes'))app.register('base_path',str(os.path.dirname(__file__)))res=app('listdata')# print: [1, 3, 22, 21, 39]res=app('dictdata')# print: {'name': 'jemes'}res=app('tupledata')# print: ('name', 'jemes')res=app('base_path')# print: /Users/jemes/workspace/simutil