Sanic: Is there a workaround of non-aio-db-client?

Created on 16 May 2017  路  5Comments  路  Source: sanic-org/sanic

Like, I need to work with both sanic and orientdb. And there is no aio version of pyorient. With tornado, I could use multi-thread as suggested by the official website. Could I just do the same with Sanic?

question

All 5 comments

As far as I know, yeah, you could go ahead and make a wrapper that executes sync calls.
Check out executors.

So basically the way to go would be something like

def asyncify(func, *args):
    async def async_wrap(*args):
        await app.loop.run_in_executor(None, func, *args)
    return async_wrap

@asyncify
def blocking_call(foo): # insert blocking stuff

Or is it a bad idea doing this?

I mean you could do it, but you would get much better performance (probably) from an async-first DB client

I had a similar problem with sqlalchemy so decided to make it work in an async fashion... A brief explanation is here https://marlinux.wordpress.com/2017/05/19/python-3-6-asyncio-sqlalchemy.
Changed the method a bit by using this module and below a simple example with the asyncio_extras ;)

    async def load_fabrics(self):
        """
        Method which loads all fabric references currently in the database
        """

        @self.threadpool
        def query():
            s = self.get_sql_session()
            try:
                return [x.to_dict() for x in s.query(FabricReference).all()]
            finally:
                s.close()

        return await query()

In case you're wondering the get_sql_session method is just a wrapper around scoped_session

I'm going to close this since it isn't really an issue with Sanic, but more of an issue with the lack of async DB clients. Please feel free to reopen if there are further questions or discussion needed.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

graingert picture graingert  路  3Comments

vlad0337187 picture vlad0337187  路  3Comments

aiurlano picture aiurlano  路  4Comments

1067511899 picture 1067511899  路  3Comments

sirex picture sirex  路  4Comments