This repository was archived by the owner on Aug 14, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconnect.py
More file actions
63 lines (43 loc) · 1.7 KB
/
connect.py
File metadata and controls
63 lines (43 loc) · 1.7 KB
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
from configparser import ConfigParser, NoOptionError, NoSectionError
from logging import basicConfig, error, INFO
from pathlib import Path
def absent(type: str, name: str = None) -> str:
'''Show warning message.
:param type: Prefix of phrase.
:param name: (optional) Object name which is missed.
:return: The message.
'''
name = ' ' + name if name else ''
return f'{type}{name} not found.'
def init(is_rabbitmq: bool = False) -> bool:
'''Initialise connection to a server.
:param is_rabbitmq: (optional) True if need to connect to the RabbitMQ
server. Otherwise, connection to the MongoDB database.
:return: True if it is done without errors.
'''
basicConfig(format='%(levelname)s: %(message)s', level=INFO)
path = Path('credentials.ini')
section = 'rabbitmq' if is_rabbitmq else 'mongodb'
try:
if not path.exists():
raise Exception(absent('Configuration file', path))
(config := ConfigParser()).read(path, 'utf-8')
options = ['user', 'password', 'host']
if is_rabbitmq:
options.append('port')
options.append('name')
try:
credentials = [config.get(section, option) for option in options]
except NoSectionError as err:
raise Exception(absent('Section', err.section))
except NoOptionError as err:
raise Exception(absent('Option', err.option))
else:
if is_rabbitmq:
from services.rabbitmq.connect import handler
else:
from services.mongodb.connect import handler
return handler(credentials)
except Exception as err:
error(err)
return False