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 pathseed.py
More file actions
72 lines (55 loc) · 1.99 KB
/
seed.py
File metadata and controls
72 lines (55 loc) · 1.99 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
64
65
66
67
68
69
70
71
72
from datetime import datetime
from json import load
from typing import Callable
from connect import absent, init
# Each model should be imported to use them from global definitions.
from services.mongodb.models import Author, Quote
def collection(
model: str,
modify: str,
modifier: Callable[[str], str],
key: str = None
) -> dict:
'''Import documents from file to collection.
:param model: Class name of collection model.
:param modify: The dictionary key from the file whose value will be changed
by the function declared in the next parameter.
:param modifier: Name of function which will edit file dictionary value
defined in the previous parameter.
:param key: (optional) Save created document identifier to function result
dictionary keyed by value from file dictionary based on a key specified
in this parameter if last one is defined.
:return: Document identifiers or empty dictionary.
'''
items = {}
collection = model.lower() + 's'
try:
with open(collection + '.json', encoding='utf-8') as file:
documents = load(file)
except FileNotFoundError as error:
print(absent('Collection file', error.filename))
else:
cls = globals()[model]
for document in documents:
document[modify] = modifier(document[modify])
entity = cls(**document).save()
if key:
items[document[key]] = entity
print(
f'{len(documents)} documents of {collection} have been '
'successfully created.'
)
finally:
return items
def main() -> None:
'''Create collections and add documents to them.'''
if init():
authors = collection(
'Author',
'born_date',
lambda date: datetime.strptime(date, '%B %d, %Y').date(),
'fullname'
)
collection('Quote', 'author', lambda name: authors[name])
if __name__ == '__main__':
main()