0

I am trying to integrate sqlalchemy with aiomysql on python 3.6, using their official example on github here is my full code

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()

but i am getting the following error

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

what am i missing in my code? I know the error is pretty obvious but how do I fix it?

1 Answer 1

1

async with can occur only inside async def . Move your code into an async def main() and call it with run_until_complete()

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.