aiomysql 和 sqlalchemy 基本示例在 python 3.6 上产生语法错误

aiomysql and sqlalchemy basic example produces syntax error on python 3.6

我正在尝试在 python 3.6 上将 sqlalchemy 与 aiomysql 集成,使用他们在 github 上的官方示例,这是我的完整代码

import sqlalchemy as sa
import asyncio
from aiomysql.sa import create_engine

DB1 = dict(host="xxx",...)
DB2 = dict(host="yyy",...)

DATABASES = dict(db1=db1, db2=db2)

async def get_engine(loop, configs):
    configs = configs.copy()
    configs['loop'] = loop
    engine = await create_engine(**configs)
    return engine

class Engine(object):
    __shared_state = {}
    running = None

    def __init__(self, loop):
        print("init", Engine.running)
        self.__dict__ = Engine.__shared_state
        self.loop = loop
        if not Engine.running:
            self.ignite(loop)

    def connect(self, key, configs, loop):
        engine = loop.run_until_complete(get_engine(loop, configs))
        self.__dict__[key] = engine

    def ignite(self, loop):
        Engine.running = True
        for key, configs in DATABASES.items():
            self.connect(key, configs, loop)

def DoMyQueries(conn):
    pass

ioloop = asyncio.get_event_loop()
engine = Engine(ioloop)
async with engine.db1.acquire() as conn:
    DoMyQueries(conn)

engine.db1.close()
await engine.wait_closed()

但我收到以下错误

 File "myfile.py", line 45
   async with engine.db1.acquire() as conn:
         ^
   SyntaxError: invalid syntax

我的代码中缺少什么?我知道错误很明显,但我该如何解决?

async with 只能出现在 async def . 中 将您的代码移动到 async def main() 中并用 run_until_complete()

调用它