如何在烧瓶中创建异步查询以进行postgress?

时间:2017-03-16 10:27:26

标签: python postgresql flash-message

我有以下阻止代码:

from flask_sqlalchemy import SQLAlchemy

def find_places():
   query = "Select ... From ... Where ..."
   result = db.session.execute(query)
   return json.dumps([dict(r) for r in result)

@app.route('/')
def videos():
    return find_places()

if __name__ == '__main__':
    db = SQLAlchemy(app)
    app.run()

如何使此代码异步?

1 个答案:

答案 0 :(得分:3)

看看aiopg,它是Python的最佳(也可能是唯一的)异步Postgres库。

他们还有可选的SQLAlchemy集成。我只是从自述文件中复制:

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())