Explorar el Código

Optimize API-Hour Container for PostgreSQL

Ludovic Gasc (GMLudo) hace 10 años
padre
commit
9b00e4d932
Se han modificado 1 ficheros con 16 adiciones y 22 borrados
  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