执行了不等待结果? 异步操作MySQL:Tornado-MySQL

来源:互联网 发布:傲剑易经升级数据大全 编辑:程序博客网 时间:2024/05/16 03:44

This package contains a fork of PyMySQL supporting Tornado.

WARNING

This library is experimental. Don't use for production unless you can fix problem yourself.

If you think async is efficient, you're wrong. You shoud try thread before this. See also: http://techspot.zzzeek.org/2015/02/15/asynchronous-python-and-databases/

I don't have motivation to improve this library. I only fix bugs. Please don't send feature request.

Instead, you should your time and energy to port your project to asyncio and newest Python 3. Please don't pay your time to adding new feature to this project.

Example

example

#!/usr/bin/env pythonfrom __future__ import print_function

from tornado import ioloop, genimport tornado_mysql

@gen.coroutinedef main():conn = yield tornado_mysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='mysql')cur = conn.cursor()yield cur.execute("SELECT Host,User FROM user")print(cur.description)for row in cur:print(row)cur.close()conn.close()

ioloop.IOLoop.current().run_sync(main)

example_pool

#!/usr/bin/env pythonfrom __future__ import print_function

from tornado import ioloop, genfrom tornado_mysql import pools

pools.DEBUG = True

POOL = pools.Pool(dict(host='127.0.0.1', port=3306, user='root', passwd='', db='mysql'),max_idle_connections=1,max_recycle_sec=3)

@gen.coroutinedef worker(n):for i in range(10):t = 1print(n, "sleeping", t, "seconds")cur = yield POOL.execute("SELECT SLEEP(%s)", (t,))print(n, cur.fetchall())

@gen.coroutinedef main():workers = [worker(i) for i in range(10)]yield workers

ioloop.IOLoop.current().run_sync(main)print(POOL._opened_conns)

Requirements

  • Python -- one of the following:
    • CPython 2.7 or >= 3.3
    • PyPy >= 2.3.1
  • MySQL Server -- one of the following:
    • MySQL >= 4.1
    • MariaDB >= 5.1

Installation

The last stable release is available on PyPI and can be installed with pip:

$ pip install Tornado-MySQL

Test Suite

If you would like to run the test suite, first copy the file .travis.databases.json to tornado_mysql/tests/databases.jsonand edit the new file to match your MySQL configuration:

$ cp .travis.databases.json tornado_mysql/tests/databases.json$ $EDITOR tornado_mysql/tests/databases.json

To run all the tests, execute the script runtests.py:

$ python runtests.py

tox.ini file is also provided for conveniently running tests on multiple Python versions:

$ tox

Resources

DB-API 2.0: http://www.python.org/dev/peps/pep-0249

MySQL Reference Manuals: http://dev.mysql.com/doc/

MySQL client/server protocol: http://dev.mysql.com/doc/internals/en/client-server-protocol.html

PyMySQL mailing list: https://groups.google.com/forum/#!forum/pymysql-users

License

PyMySQL is released under the MIT License. See LICENSE for more information.

0 0
原创粉丝点击