3.和数据库的那些事

在开发中,数据库是必不可少的, 因此这节主要来说一下常用的两种类型数据库,mysql和redis的简单使用
  1. #1.mysql算是最常用的数据库之一了,不要钱,功能齐全,性能优良。这里主要使用tornado的一款api,
  2. #tornado_mysql。
  3. from tornado_mysql import pools
  4. from tornado import gen
  5. from tornado import ioloop
  6. from tornado.concurrent import Future
  7. from pool import threadpool
  8. import functools
  9. SYNC, ROW, DATASET = range(3)
  10. __pool = None
  11. ioloop = ioloop.IOLoop.current()
  12. def init(**conf):
  13. global __pool
  14. if not __pool:
  15. __pool = pools.Pool(conf, max_idle_connections=5, max_recycle_sec=3)
  16. @gen.coroutine
  17. def execute(sql, value=None, operator=SYNC):
  18. assert __pool is not None
  19. result = None
  20. if value is None:
  21. cur = yield __pool.execute(sql)
  22. else:
  23. yield __pool.execute(sql, value)
  24. if operator == ROW:
  25. result = cur.fetchone()
  26. elif operator == DATASET:
  27. result = cur.fetchall()
  28. raise gen.Return(result)
  29. fetchone = functools.partial(execute, operator=ROW)
  30. fetchall = functools.partial(execute, operator=DATASET)
  31. #对几种简单的数据库操作进行了简单的封装,便于开发中的使用。
  1. #2.redis算是比较常用的数据库之一,一般使用来做cache,也有做消息队列的。这里用的是
  2. #tornadoredis这款api。
  3. import tornadoredis
  4. from tornado import gen
  5. from tornado.concurrent import Future
  6. pool = None
  7. def init():
  8. global pool
  9. if not pool:
  10. CONNECTION_POOL = tornadoredis.ConnectionPool(max_connections=500, wait_for_available=True)
  11. pool = tornadoredis.Client(connection_pool=CONNECTION_POOL, selected_db=12)
  12. @gen.coroutine
  13. def close():
  14. if pool:
  15. yield pool.disconnect()
  16. @gen.coroutine
  17. def batch(commands):
  18. assert pool is not None
  19. result = None
  20. try:
  21. pipe = pool.pipeline()
  22. for _cmd in commands:
  23. _op = _cmd[0]
  24. _args = _cmd[1]
  25. if len(_cmd) > 2:
  26. _kwargs = _cmd[2]
  27. else:
  28. _kwargs = {}
  29. getattr(pipe, _op)(*args, **kwargs)
  30. result = yield gen.Task(pipe.execute)
  31. except Exception as e:
  32. print e
  33. raise Return(result)
  34. def execute(cmd, *args, **kwargs):
  35. assert pool is not None
  36. f = Future()
  37. def onResult(result):
  38. f.set_result(result)
  39. result = None
  40. _func = getattr(pool, cmd)
  41. _func(callback=onResult, *args, **kwargs)
  42. return f
  43. #对redis的操作进行了统一封装,直接使用execute就可以, 将命令作为参数传递。多个命令的执行可以使用batch来执行, 使用pipe提高执行效率。