Skip to content

Instantly share code, notes, and snippets.

@pauleveritt
Created July 31, 2020 19:48
Show Gist options
  • Save pauleveritt/b2ac2660dec606b719f5440e8a48d556 to your computer and use it in GitHub Desktop.
Save pauleveritt/b2ac2660dec606b719f5440e8a48d556 to your computer and use it in GitHub Desktop.
Demo showing singletons added in a bound container, aren't updated in another.
from dataclasses import dataclass
from wired import ServiceRegistry
@dataclass
class CustomerOne:
name: str
@dataclass
class CustomerTwo:
name: str
@dataclass
class PageContext:
page_name: str
def main():
registry = ServiceRegistry()
site_container = registry.create_container(context=None)
# This site will render two "pages". Each has a resource
# as the context and some extra information from "the system"
# as PageContext.
pages = (
(CustomerOne('One'), PageContext('index')),
(CustomerOne('Two'), PageContext('another_page')),
)
for (this_context, this_page_context) in pages:
# Make a "sub-container" for this request, bound to the
# context of the customer.
request_container = site_container.bind(context=this_context)
# Register the PageContext so it can be used elsewhere
request_container.register_singleton(this_page_context, PageContext)
# ...later on in the processing, something wants to get, from
# the per-request subcontainer, the per-request PageContext
result: PageContext = request_container.get(PageContext)
# Alas, the second pass through, doesn't have the second page_name.
# The first pass through filled the cache, and the "subcontainer"
# doesn't seem to have cache isolation from the previous container.
result: PageContext = request_container.get(PageContext)
assert this_page_context.page_name == result.page_name
# Doesn't matter, but just in case, do some cleanup
del request_container
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment