world.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import asyncio
  2. from random import randint
  3. from operator import itemgetter
  4. @asyncio.coroutine
  5. def get_random_record(container):
  6. pg = yield from container.engines['pg']
  7. with (yield from pg.cursor()) as cur:
  8. yield from cur.execute('SELECT id AS "Id", randomnumber AS "RandomNumber" FROM world WHERE id=%(idx)s LIMIT 1',
  9. {'idx': randint(1, 10000)})
  10. world = yield from cur.fetchone()
  11. return world
  12. @asyncio.coroutine
  13. def get_random_records(container, limit):
  14. pg = yield from container.engines['pg']
  15. results = []
  16. with (yield from pg.cursor()) as cur:
  17. for i in range(limit):
  18. yield from cur.execute('SELECT id AS "Id", randomnumber AS "RandomNumber" FROM world WHERE id=%(idx)s LIMIT 1',
  19. {'idx': randint(1, 10000)})
  20. results.append((yield from cur.fetchone()))
  21. return results
  22. @asyncio.coroutine
  23. def update_random_records(container, limit):
  24. results = []
  25. pg = yield from container.engines['pg']
  26. with (yield from pg.cursor()) as cur:
  27. for i in range(limit):
  28. yield from cur.execute('SELECT id AS "Id", randomnumber AS "RandomNumber" FROM world WHERE id=%(idx)s LIMIT 1',
  29. {'idx': randint(1, 10000)})
  30. world = yield from cur.fetchone()
  31. yield from cur.execute('UPDATE world SET randomnumber=%(random_number)s WHERE id=%(idx)s',
  32. {'random_number': randint(1, 10000), 'idx': world['Id']})
  33. results.append(world)
  34. return results
  35. @asyncio.coroutine
  36. def get_fortunes(container):
  37. pg = yield from container.engines['pg']
  38. with (yield from pg.cursor()) as cur:
  39. yield from cur.execute('SELECT * FROM fortune')
  40. fortunes = yield from cur.fetchall()
  41. fortunes.append({'id': 0, 'message': 'Additional fortune added at request time.'})
  42. fortunes.sort(key=itemgetter('message'))
  43. return fortunes