【问题标题】:aiomysql and sqlalchemy basic example produces syntax error on python 3.6aiomysql 和 sqlalchemy 基本示例在 python 3.6 上产生语法错误
【发布时间】:2017-08-10 19:08:06
【问题描述】:

我正在尝试在 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

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

【问题讨论】:

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


    【解决方案1】:

    async with 只能出现在 async def .

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-20
      • 2010-09-22
      • 2017-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-20
      相关资源
      最近更新 更多