Python 如何在flask中创建对postgress的异步查询?
我有以下阻止代码:Python 如何在flask中创建对postgress的异步查询?,python,postgresql,flash-message,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_place
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()
如何使这段代码异步?请看一看,它是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())