aiopg

 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
def dict_id(d):
res = {}
if isinstance(d, dict):
d = [d]
for v in d:
res[v['id']] = v
return res
def normalizr(main=None, **kwargs):
res = {}
res['entities'] = {}
if main:
res['result'] = {x['id'] for x in kwargs[main]}
for k, v in kwargs.items():
res['entities'][k] = dict_id(v)
return res
@asyncio.coroutine
def get_topic(request, *, id=1):
session = yield from get_session(request)
query = Topic.select().where(Topic.c.id == id)
with (yield from request.app['database']) as conn:
res = yield from conn.execute(query)
res = yield from res.first()
topic = dict(res)
posts_id = list(set(topic['posts']))
query = Post.select().where(Post.c.id.in_(posts_id))
with (yield from request.app['database']) as conn:
res = yield from conn.execute(query)
res = yield from res.fetchall()
posts = to_tuple(res)
user_id = list({x['user_id'] for x in posts})
query = User.select().where(User.c.id.in_(posts_id))
with (yield from request.app['database']) as conn:
res = yield from conn.execute(query)
res = yield from res.fetchall()
users = to_tuple(res)
res = normalizr('posts', posts=posts, users=users, topic=topic)
return res