2017-03-19 33 views
0

我想的SQLAlchemy與aiomysql對蟒蛇3.6使用他們的官方例如在github這裏融合,是我的全部代碼aiomysql和SQLAlchemy的基本的例子產生於Python語法錯誤3.6

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

async with只能出現內部async def .移動你的代碼到一個async def main()run_until_complete()

叫它