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

时间:2017-03-19 14:33:31

标签: python-3.x sqlalchemy python-asyncio

我正在尝试将sqlalchemy与aiomysql集成在python 3.6上,使用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

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

1 个答案:

答案 0 :(得分:1)

async with只能在async def .内发生。将您的代码移到async def main()并使用run_until_complete()调用