Browse Source

Merge pull request #1428 from Eyepea/fix_pgsql_cursor_handling

Fix pgsql cursor handling
Mike Smith 10 years ago
parent
commit
2ee141f5fd
1 changed files with 16 additions and 22 deletions
  1. 16 22
      frameworks/Python/API-Hour/hello/hello/services/world.py

+ 16 - 22
frameworks/Python/API-Hour/hello/hello/services/world.py

@@ -14,35 +14,29 @@ def get_random_record(container):
 
 @asyncio.coroutine
 def get_random_records(container, limit):
-    tasks = []
+    pg = yield from container.engines['pg']
     results = []
-    for i in range(limit):
-        tasks.append(container.loop.create_task(get_random_record(container)))
-    yield from asyncio.wait(tasks)
-    for task in tasks:
-        results.append(task.result())
+    with (yield from pg.cursor()) as cur:
+        for i in range(limit):
+            yield from cur.execute('SELECT id AS "Id", randomnumber AS "RandomNumber" FROM world WHERE id=%(idx)s LIMIT 1',
+                                   {'idx': randint(1, 10000)})
+            results.append((yield from cur.fetchone()))
+
     return results
 
 @asyncio.coroutine
-def update_random_record(container):
+def update_random_records(container, limit):
+    results = []
     pg = yield from container.engines['pg']
 
-    world = yield from get_random_record(container)
-
     with (yield from pg.cursor()) as cur:
-        yield from cur.execute('UPDATE world SET randomnumber=%(random_number)s WHERE id=%(idx)s',
-                               {'random_number': randint(1, 10000), 'idx': world['Id']})
-    return world
-
[email protected]
-def update_random_records(container, limit):
-    tasks = []
-    results = []
-    for i in range(limit):
-        tasks.append(container.loop.create_task(update_random_record(container)))
-    yield from asyncio.wait(tasks)
-    for task in tasks:
-        results.append(task.result())
+        for i in range(limit):
+            yield from cur.execute('SELECT id AS "Id", randomnumber AS "RandomNumber" FROM world WHERE id=%(idx)s LIMIT 1',
+                                   {'idx': randint(1, 10000)})
+            world = yield from cur.fetchone()
+            yield from cur.execute('UPDATE world SET randomnumber=%(random_number)s WHERE id=%(idx)s',
+                                   {'random_number': randint(1, 10000), 'idx': world['Id']})
+            results.append(world)
     return results
 
 @asyncio.coroutine