-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathbootstrapdb.py
More file actions
100 lines (78 loc) · 2.15 KB
/
bootstrapdb.py
File metadata and controls
100 lines (78 loc) · 2.15 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
from random import choice
from faker import Faker
from sqlalchemy.exc import IntegrityError
from models import Base, Author, Article, Hashtag
from session import session
def create_authors(count=50):
fake = Faker()
return [
Author(
first_name=fake.first_name(),
last_name=fake.last_name(),
login=fake.user_name(),
salary=fake.pyfloat(
min_value=4000,
max_value=10_000
),
email=fake.email(),
)
for _ in range(count)
]
def create_article(author_id):
fake = Faker()
return Article(
title=fake.sentence(),
content=fake.text(),
author_id=author_id,
)
def create_articles(author_id, count=10):
return [
create_article(author_id)
for _ in range(count)
]
def create_hashtags(count=10):
fake = Faker()
hashtags = set()
while len(hashtags) < count:
hashtags.add(fake.word())
return [
Hashtag(name=hashtag)
for hashtag in hashtags
]
def assign_hashtags_to_articles(hashtags, articles):
for article in articles:
hashtag = choice(hashtags)
article.hashtags.append(hashtag)
def main():
# Create all tables
Base.metadata.create_all()
# Create authors
authors = create_authors(count=1000)
for author in authors:
print(f"Adding author {author.login}")
try:
session.add(author)
session.commit()
except IntegrityError:
session.rollback()
print(f"Author {author.login} already exists")
# Create articles
author = choice(authors)
articles = create_articles(author_id=author.id)
session.add_all(articles)
session.commit()
# Create hashtags
hashtags = create_hashtags(count=100)
try:
session.add_all(hashtags)
session.commit()
except IntegrityError:
session.rollback()
# Assign hashtags to articles
try:
assign_hashtags_to_articles(hashtags, articles)
session.commit()
except IntegrityError:
session.rollback()
if __name__ == "__main__":
main()