Snippets

Misha Behersky ORM in executor

Created by Misha Behersky
import asyncio
import time

from aiohttp import web
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base


Base = declarative_base()


class User(Base):
    __tablename__ = 'tbl_user'

    id = Column(Integer, primary_key=True)
    name = Column(String(50), nullable=True)
    
    @classmethod
    def long_sync(cls):
      # Some query on db
      time.sleep(5)
      return 'Data from db'

@asyncio.coroutine  
def sync_db(func):
    loop = asyncio.get_event_loop()
    result = loop.run_in_executor(None, func) 
    return result


@asyncio.coroutine
def handle(request):
    data = yield from sync_db(User.long_sync)
    text = 'Hello, ' + data
    return web.Response(body=text.encode('utf-8'))


@asyncio.coroutine
def init(loop):
    app = web.Application(loop=loop)
    app.router.add_route('GET', '/', handle)

    srv = yield from loop.create_server(app.make_handler(), '127.0.0.1', 8080)
    print("Server started at http://127.0.0.1:8080")
    return srv


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(init(loop))
    try:
        loop.run_forever()
    except KeyboardInterrupt:
      pass

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.