Package: aio-task-bound-context
AIO Task Bound ContextContext manager that provides a means for context to be set, and retrieved
in Python AsyncIO.What???Okay so for a concrete example, thing of how Flask handles the current request:fromflaskimportrequestThis import, called from anywhere, will import the current request being
handled. This is made possible in a way similar to this:request=Nonedefget_request():returnrequestdefset_request(value):globalrequestrequest=valueWhen the HTTP server gets a request, it will callset_request, then anywhere
in the code another function can callget_requestto get the value.Here's the kicker: This is not possible with AIO, because multiple tasks may
be running at once, so there are multiple values forrequest, rather than
just a single value. Imagine the same piece of code being used in AIO:importasyncioasaioasyncdefhandle_request(request):set_request(request)# generate the responseawaitaio.sleep(1)assertget_request()==request# will failset_request(None)aio.get_event_loop().run_until_complete(aio.gather(handle_request('value 1'),handle_request('value 2'),))Obviously, this is going to be problematic.The answeraio_task_bound_contextattaches a stack of the current context values to the
currentTask, as well as tracking the parent tasks so that their context
can be inherrited:importasyncioasaiofromaio_task_bound_contextimportset_task_factory,TaskBoundContextclassRequestContext(TaskBoundContext):def__init__(self,request):self.request=requestdefget_value(self):returnself.requestasyncdefhandle_request(request):withRequestContext(request):# generate the responseawaitaio.sleep(1)assertRequestContext.current()==request# will succeedloop=aio.get_event_loop()set_task_factory(loop=loop)loop.run_until_complete(aio.gather(handle_request('value 1'),handle_request('value 2'),))ExamplesNote that all these examples will work in async tasks, which is what makes
them more special than a simple context manager. They are all simple examples
outside an async environment, but don't be fooled by the hidden complexity.To start off, we need to replace the default task factory inasynciowith
a wrapper to add extra details to tasks. Assume this has been executed before
all examples:importasyncioasaiofromaio_task_bound_contextimportcreate_task_factory,TaskBoundContextloop=aio.get_event_loop()loop.set_task_factory(create_task_factory(loop=loop))With noget_valuefunction defined, the "value" is theTaskBoundContextitself, so you can setup values in the__init__function if you just want
to pass around as set of values.classExampleContext(TaskBoundContext):def__init__(self,*args,**kwargs):super().__init__()self.args=argsself.kwargs=kwargswithExampleContext('an arg',key='in kwargs'):assertExampleContext.current().args==['an arg']assertExampleContext.current().kwargs=={'key':'in kwargs'}The "as value" of the context manager is the value returned fromget_value.classExampleContext(TaskBoundContext):def__init__(self,value):super().__init__()self.value=valuedefget_value(self):returnself.valuewithExampleContext('test')asvalue:assertvalue=='test'withExampleContext('different')asvalue:assertvalue=='different'Contexts are a hierarchical stack, so you can have multiple contexts and they
will push/pop their values onto/off of the stack of contexts.classExampleContext(TaskBoundContext):def__init__(self,value):super().__init__()self.value=valuedefget_value(self):returnself.valuewithExampleContext('first'):assertExampleContext.current()=='first'withExampleContext('second'):assertExampleContext.current()=='second'assertExampleContext.current()=='firstTheget_valuefunction can accept a single argument, which is the current
value of the stack.classLoggerContext(TaskBoundContext):def__init__(self,suffix):super().__init__()self.suffix=suffixdefget_value(self,current):ifcurrentisNone:returnlogging.getLogger(self.suffix)else:returncurrent.getChild(self.suffix)TestingPython 3.5+ is supported. To run tests across all environments, we usepyenv, and some quickvirtualenvinvocations (yes, we could also usetox).To run the tests, just run./tests_runall.shwhich will install relevant
Python versions if not already installed, create virtualenvs for them, and
runtests.py.To run tests manually, simply./test.py.LicenseCopyright 2018 Ricky CookPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.