1# These comments let tutorial-asyncio.rst include this code in sections. 2# -- setup-start -- 3import asyncio 4 5from aiohttp import web 6from motor.motor_asyncio import AsyncIOMotorClient 7 8 9@asyncio.coroutine 10def setup_db(): 11 db = AsyncIOMotorClient().test 12 yield from db.pages.drop() 13 html = '<html><body>{}</body></html>' 14 yield from db.pages.insert_one({'_id': 'page-one', 15 'body': html.format('Hello!')}) 16 17 yield from db.pages.insert_one({'_id': 'page-two', 18 'body': html.format('Goodbye.')}) 19 20 return db 21# -- setup-end -- 22 23 24# -- handler-start -- 25@asyncio.coroutine 26def page_handler(request): 27 # If the visitor gets "/pages/page-one", then page_name is "page-one". 28 page_name = request.match_info.get('page_name') 29 30 # Retrieve the long-lived database handle. 31 db = request.app['db'] 32 33 # Find the page by its unique id. 34 document = yield from db.pages.find_one(page_name) 35 36 if not document: 37 return web.HTTPNotFound(text='No page named {!r}'.format(page_name)) 38 39 return web.Response(body=document['body'].encode(), 40 content_type='text/html') 41# -- handler-end -- 42 43# -- main-start -- 44loop = asyncio.get_event_loop() 45db = loop.run_until_complete(setup_db()) 46app = web.Application() 47app['db'] = db 48# Route requests to the page_handler() coroutine. 49app.router.add_get('/pages/{page_name}', page_handler) 50web.run_app(app) 51# -- main-end -- 52