Skip to content

Commit 8d073ae

Browse files
Chapter 11: Generate fake users and posts (11c)
1 parent f9e8733 commit 8d073ae

File tree

4 files changed

+40
-0
lines changed

4 files changed

+40
-0
lines changed

app/fake.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
from random import randint
2+
from sqlalchemy.exc import IntegrityError
3+
from faker import Faker
4+
from . import db
5+
from .models import User, Post
6+
7+
8+
def users(count=100):
9+
fake = Faker()
10+
i = 0
11+
while i < count:
12+
u = User(email=fake.email(),
13+
username=fake.user_name(),
14+
password='password',
15+
confirmed=True,
16+
name=fake.name(),
17+
location=fake.city(),
18+
about_me=fake.text(),
19+
member_since=fake.past_date())
20+
db.session.add(u)
21+
try:
22+
db.session.commit()
23+
i += 1
24+
except IntegrityError:
25+
db.session.rollback()
26+
27+
28+
def posts(count=100):
29+
fake = Faker()
30+
user_count = User.query.count()
31+
for i in range(count):
32+
u = User.query.offset(randint(0, user_count - 1)).first()
33+
p = Post(body=fake.text(),
34+
timestamp=fake.past_date(),
35+
author=u)
36+
db.session.add(p)
37+
db.session.commit()
File renamed without changes.

requirements/dev.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
-r common.txt
2+
faker==0.7.18

requirements/prod.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
-r common.txt

0 commit comments

Comments
 (0)