Skip to content

Commit 2ee141f

Browse files
Merge pull request TechEmpower#1428 from Eyepea/fix_pgsql_cursor_handling
Fix pgsql cursor handling
2 parents 1c61cc0 + 9b00e4d commit 2ee141f

File tree

1 file changed

+16
-22
lines changed
  • frameworks/Python/API-Hour/hello/hello/services

1 file changed

+16
-22
lines changed

frameworks/Python/API-Hour/hello/hello/services/world.py

Lines changed: 16 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -14,35 +14,29 @@ def get_random_record(container):
1414

1515
@asyncio.coroutine
1616
def get_random_records(container, limit):
17-
tasks = []
17+
pg = yield from container.engines['pg']
1818
results = []
19-
for i in range(limit):
20-
tasks.append(container.loop.create_task(get_random_record(container)))
21-
yield from asyncio.wait(tasks)
22-
for task in tasks:
23-
results.append(task.result())
19+
with (yield from pg.cursor()) as cur:
20+
for i in range(limit):
21+
yield from cur.execute('SELECT id AS "Id", randomnumber AS "RandomNumber" FROM world WHERE id=%(idx)s LIMIT 1',
22+
{'idx': randint(1, 10000)})
23+
results.append((yield from cur.fetchone()))
24+
2425
return results
2526

2627
@asyncio.coroutine
27-
def update_random_record(container):
28+
def update_random_records(container, limit):
29+
results = []
2830
pg = yield from container.engines['pg']
2931

30-
world = yield from get_random_record(container)
31-
3232
with (yield from pg.cursor()) as cur:
33-
yield from cur.execute('UPDATE world SET randomnumber=%(random_number)s WHERE id=%(idx)s',
34-
{'random_number': randint(1, 10000), 'idx': world['Id']})
35-
return world
36-
37-
@asyncio.coroutine
38-
def update_random_records(container, limit):
39-
tasks = []
40-
results = []
41-
for i in range(limit):
42-
tasks.append(container.loop.create_task(update_random_record(container)))
43-
yield from asyncio.wait(tasks)
44-
for task in tasks:
45-
results.append(task.result())
33+
for i in range(limit):
34+
yield from cur.execute('SELECT id AS "Id", randomnumber AS "RandomNumber" FROM world WHERE id=%(idx)s LIMIT 1',
35+
{'idx': randint(1, 10000)})
36+
world = yield from cur.fetchone()
37+
yield from cur.execute('UPDATE world SET randomnumber=%(random_number)s WHERE id=%(idx)s',
38+
{'random_number': randint(1, 10000), 'idx': world['Id']})
39+
results.append(world)
4640
return results
4741

4842
@asyncio.coroutine

0 commit comments

Comments
 (0)