import asyncio
import logging
import pathlib

import aiohttp_jinja2
import jinja2
from aiohttp import web

from aiohttp_polls.routes import setup_routes
from aiohttp_polls.utils import init_postgres, load_config
from aiohttp_polls.views import SiteHandler


PROJ_ROOT = pathlib.Path(__file__).parent.parent
TEMPLATES_ROOT = pathlib.Path(__file__).parent / 'templates'
log = logging.getLogger(__name__)


async def init(loop):
    # setup application and extensions
    app = web.Application(loop=loop)
    aiohttp_jinja2.setup(
        app, loader=jinja2.FileSystemLoader(str(TEMPLATES_ROOT)))
    # load config from yaml file
    conf = load_config(str(PROJ_ROOT / 'config' / 'polls.yaml'))
    # create connection to the database
    pg = await init_postgres(conf['postgres'], loop)
    # setup views and routes
    handler = SiteHandler(pg)
    setup_routes(app, handler, PROJ_ROOT)

    # init logging and attach access_log
    logging.basicConfig(level=logging.DEBUG)
    app_handler = app.make_handler(access_log=log)
    host, port = conf['host'], conf['port']
    srv = await loop.create_server(app_handler, host, port)
    print("Server started at http://{0}:{1}".format(host, port))
    return srv, app_handler


loop = asyncio.get_event_loop()
srv, app_handler = loop.run_until_complete(init(loop))

try:
    loop.run_forever()
except KeyboardInterrupt:
    pass
finally:
    loop.run_until_complete(app_handler.finish_connections())
    srv.close()
    loop.run_until_complete(srv.wait_closed())
loop.close()

@@ -685,16 +685,17 @@
 yaml'))%0A
+%0A
     # cr
@@ -775,24 +775,134 @@
 es'%5D, loop)%0A
+%0A    async def close_pg():%0A        pg.close()%0A        await pg.wait_closed()%0A%0A    app.register_on_finish(pg)%0A%0A
     # setup 
@@ -1327,16 +1327,32 @@
 ndler%0A%0A%0A
+def main():%0A    
 loop = a
@@ -1375,16 +1375,20 @@
 _loop()%0A
+    
 srv, app
@@ -1439,13 +1439,21 @@
 ))%0A%0A
+    
 try:%0A
+    
     
@@ -1471,16 +1471,20 @@
 rever()%0A
+    
 except K
@@ -1501,16 +1501,20 @@
 errupt:%0A
+    
     pass
@@ -1514,16 +1514,20 @@
    pass%0A
+    
 finally:
@@ -1527,24 +1527,147 @@
 inally:%0A    
+    srv.close()%0A        loop.run_until_complete(srv.wait_closed())%0A        loop.run_until_complete(app.shutdown())%0A        
 loop.run_unt
@@ -1678,20 +1678,16 @@
 omplete(
-app_
 handler.
@@ -1709,27 +1709,31 @@
 ons(
-))%0A    srv.close()%0A
+shutdown_timeout))%0A    
     
@@ -1760,36 +1760,75 @@
 ete(
-srv.wait_closed())%0Aloop.close
+app.finish())%0A    loop.close()%0A%0A%0Aif __name__ == '__main__':%0A    main
 ()%0A

Fix finalization procedure, allow python -m aiohttp_polls.main