-
Notifications
You must be signed in to change notification settings - Fork 9
/
bootstrapdb.py
80 lines (60 loc) · 1.77 KB
/
bootstrapdb.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
79
80
import random
from faker import Faker
from sqlalchemy.exc import IntegrityError
from models import Base, Author, Article, Hashtag
from session import session
def generate_authors(session, count=50):
fake = Faker()
session.add_all([
Author(
first_name=fake.first_name(),
last_name=fake.last_name(),
user_name=fake.user_name(),
email=fake.email(),
)
for _ in range(count)
])
session.commit()
def generate_articles(session, count=10):
fake = Faker()
for author in session.query(Author):
author.articles.extend([
Article(
title=fake.sentence(),
content=fake.text(),
)
for _ in range(count)
])
session.commit()
def generate_hashtags(session, count=10):
fake = Faker()
total_hashtags = 0
while total_hashtags < count:
hashtag = Hashtag(name=fake.word())
try:
session.add(hashtag)
total_hashtags += 1
except IntegrityError:
session.rollback()
def assign_hashtags(session):
all_hashtags = session.query(Hashtag).all()
for article in session.query(Article):
hashtags = random.choices(
all_hashtags, k=random.randint(1, 5)
)
article.hashtags.extend(set(hashtags))
session.commit()
def main():
print("Creating database tables...")
Base.metadata.create_all()
print("Generating authors...")
generate_authors(session)
print("Generating articles...")
generate_articles(session)
print("Generating hashtags...")
generate_hashtags(session)
print("Assigning hashtags to articles...")
assign_hashtags(session)
print("Done!")
if __name__ == "__main__":
main()