将视图绑定到aiohttp的异常
aiohttp_exc_handlers的Python项目详细描述
用法
importasynciofromaiohttpimportwebfromaiohttp_exc_handlersimport(exc_handlers_middleware,bind_exc_handler,)classCustomException(Exception):passasyncdefcustom_exception_handler(request,exc):returnweb.Response(text="Hello, {!s}!".format(exc))asyncdefhello(request):raiseCustomException('world')# add middlewareapp=web.Application(middlewares=[exc_handlers_middleware])# bind handler to exceptionbind_exc_handler(app,CustomException,custom_exception_handler)app.router.add_route('GET','/',hello)loop=asyncio.get_event_loop()handler=app.make_handler()f=loop.create_server(handler,'0.0.0.0',8080)srv=loop.run_until_complete(f)try:loop.run_forever()exceptKeyboardInterrupt:passfinally:loop.run_until_complete(handler.finish_connections(1.0))srv.close()loop.run_until_complete(srv.wait_closed())loop.run_until_complete(app.finish())loop.close()
测试
$ pip install pytest $ py.test tests.py