-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
49 lines (35 loc) · 1017 Bytes
/
app.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
import requests
from models import Post, PostJSON, Session
def main():
session = Session()
items = get_items()
if items:
delete_items(session)
save_items(items, session)
session.commit()
session.close()
def get_items():
"""Get posts from API."""
endpoint = 'https://jsonplaceholder.typicode.com/posts'
r = requests.get(endpoint)
return r.json()
def save_items(items, session):
"""Save posts to DB."""
for item in items:
# relational
post = Post()
post.id = item['id']
post.userId = item['userId']
post.title = item['title']
post.body = item['body']
session.add(post)
# json
post_json = PostJSON()
post_json.data = item
session.add(post_json)
def delete_items(session):
"""Delete all posts."""
session.query(Post).delete(synchronize_session=False)
session.query(PostJSON).delete(synchronize_session=False)
if __name__ == "__main__":
main()