bwangel23
10/19/2016 - 1:27 AM

write a async context manager for tormysql

write a async context manager for tormysql

#!/usr/bin/env python3
# -*- coding: utf-8 -*-


from tornado.ioloop import IOLoop
import tormysql

class get_cursor:
    def __init__(self, pool):
        self.pool = pool

    async def __aenter__(self):
        self.tx = await self.pool.begin()
        return self.tx

    async def __aexit__(self, exc_type, exc, tb):
        if tb is None:
            await self.tx.commit()
        else:
            await self.tx.rollback()

async def insert():
    pool = tormysql.helpers.ConnectionPool(
        max_connections = 20, #max open connections
        idle_seconds = 7200, #conntion idle timeout time, 0 is not timeout
        wait_connection_timeout = 3, #wait connection timeout
        host = "127.0.0.1",
        user = "root",
        passwd = "deepin",
        db = "test",
        charset = "utf8"
    )
    async with get_cursor(pool) as cursor:
        await cursor.execute("INSERT INTO test(id) VALUES(1)")

ioloop = IOLoop.instance()
ioloop.run_sync(insert)