Browse Source

Chapter 11: Generate fake users and posts (11c)

T. Meissner 1 year ago
parent
commit
3c68168f40
5 changed files with 42 additions and 1 deletions
  1. 37
    0
      app/fake.py
  2. 1
    1
      app/templates/user.html
  3. 0
    0
      requirements/common.txt
  4. 3
    0
      requirements/dev.txt
  5. 1
    0
      requirements/prod.txt

+ 37
- 0
app/fake.py View File

@@ -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()

+ 1
- 1
app/templates/user.html View File

@@ -26,7 +26,7 @@
26 26
             <p>
27 27
                 Member since {{ moment(user.member_since).format('L') }}.
28 28
                 Last seen {{ moment(user.last_seen).fromNow() }}.
29
-                <p>{{ user.posts.count() }} blog posts.</p>
29
+                <p>{{ user.posts.count() }} blog post{% if user.posts.count() > 1 %}s{% endif %}.</p>
30 30
             </p>
31 31
             <p>
32 32
                 {% if user == current_user %}

requirements.txt → requirements/common.txt View File


+ 3
- 0
requirements/dev.txt View File

@@ -0,0 +1,3 @@
1
+-r common.txt
2
+Faker==1.0.0
3
+text-unidecode==1.2

+ 1
- 0
requirements/prod.txt View File

@@ -0,0 +1 @@
1
+-r common.txt