-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathrun.py
78 lines (65 loc) · 2.76 KB
/
run.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import logging
from logging.handlers import TimedRotatingFileHandler
from log import logger, formatter
from pathlib import Path
from sqlalchemy import create_engine
from config import BASE_DIR, db_driver, config_title, log_config, database_config, jdy_config, queue_config, \
sync_config, wechat_config
from api import JianDaoYun
from database_queue import Queue, OracleQueue, MssqlQueue
from queue_consumer import Consumer as QueueConsumer
from handlers import ContactsHandler
from args import args as run_args
from notifications.channels import WeChatChannel
def init_queue(config, engine) -> Queue:
logger.info('初始化队列')
_queues = {
'mssql': MssqlQueue,
'oracle': OracleQueue
}
queue = _queues[db_driver.lower()](engine=engine, config=config)
return queue
def init_logger(config):
file_name = config.file_name
full_file_name = Path.joinpath(BASE_DIR, file_name)
file_handler = TimedRotatingFileHandler(filename=full_file_name, encoding='utf-8', when='midnight', interval=1,
backupCount=5)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
if run_args.debug or config.debug:
logging.getLogger().setLevel(logging.DEBUG)
else:
logging.getLogger().setLevel(logging.INFO)
logger.info(f'初始化日志')
logger.info(f'加载配置 >>> {config_title} <<<,数据库类型 >>> {db_driver} <<<')
def init_channel(config):
channel = WeChatChannel(config)
return channel
if __name__ == '__main__':
try:
init_logger(log_config)
db_engine = create_engine(database_config.uri)
db_queue = init_queue(queue_config, db_engine)
jdy_api = JianDaoYun(jdy_config)
wechat_channel = init_channel(wechat_config)
except Exception as e:
logger.error('初始化错误,请检查配置。', exc_info=True)
raise e
try:
if run_args.daemon:
queue_consumer = QueueConsumer(queue=db_queue, api=jdy_api, channel=wechat_channel)
queue_consumer.start()
except Exception as e:
logger.error('消费者程序因未知异常退出。')
raise e
try:
if run_args.sync:
departments_response = jdy_api.fetch_department_list(dept_id='root', has_child=True)
departments = departments_response.json()['departments']
users_response = jdy_api.fetch_member_list(dept_id='root', has_child=True)
users = users_response.json()['users']
contacts_handler = ContactsHandler(engine=db_engine, config=sync_config)
contacts_handler.handle(users=users, departments=departments)
except Exception as e:
logger.error('同步程序因未知异常退出。', exc_info=True)
raise e