How to make SQLAlchemy in Tornado to be async?

前端 未结 5 427
花落未央
花落未央 2020-12-02 05:11

How to make SQLAlchemy in Tornado to be async ? I found example for MongoDB on async mongo example but I couldn\'t find anything like

5条回答
  •  一向
    一向 (楼主)
    2020-12-02 05:37

    I had this same issue in the past and I couldn't find a reliable Async-MySQL library. However there is a cool solution using Asyncio + Postgres. You just need to use the aiopg library, which comes with SQLAlchemy support out of the box:

    import asyncio
    from aiopg.sa import create_engine
    import sqlalchemy as sa
    
    metadata = sa.MetaData()
    
    tbl = sa.Table('tbl', metadata,
        sa.Column('id', sa.Integer, primary_key=True),
        sa.Column('val', sa.String(255)))
    
    async def create_table(engine):
        async with engine.acquire() as conn:
            await conn.execute('DROP TABLE IF EXISTS tbl')
            await conn.execute('''CREATE TABLE tbl (
                                      id serial PRIMARY KEY,
                                      val varchar(255))''')
    
    async def go():
        async with create_engine(user='aiopg',
                                 database='aiopg',
                                 host='127.0.0.1',
                                 password='passwd') as engine:
    
            async with engine.acquire() as conn:
                await conn.execute(tbl.insert().values(val='abc'))
    
                async for row in conn.execute(tbl.select()):
                    print(row.id, row.val)
    
    loop = asyncio.get_event_loop()
    loop.run_until_complete(go())
    

    Updated as mentioned by @cglacet

提交回复
热议问题