Skip to content
Myr

complex.rst

This file

Path

docs/complex.rst

219 lines · 7.5 KiB

Last changed by

Added support for object ensuringArmin Ronacherbefore adoption8512acd

History of this file

Take it

1.. _complex-guide:23Complex Applications4====================56.. currentmodule:: click78Click is designed to write complex and simple CLI tools alike.  However9the power of its design is the ability to arbitrarily nest systems10together.  For instance in case you have ever used Django you will have11realized that it provides a command line utility.  But so does Celery for12instance.  So when using Celery with Django there are two tools that need13to interact with each other and be cross configured.1415In a theoretical world of two separate Click command line utilities they16can solve this problem by nesting one inside the other.  For instance the17web framework could also load the commands for the message queue18framework.1920Basic Concepts21--------------2223To understand how this works you need to understand two concepts: contexts24and the calling convention.2526Contexts27````````2829Whenever a Click command is executed a :class:`Context` object is created30which holds state for this particular invocation.  For instance it31remembers parsed parameters, what command created it, which resources need32to be cleaned up at the end of the function and so forth.  It also holds33an application defined object optionally.3435Context objects build a linked list until they hit top one.  Each context36is linked to the parent context.  This allows a command to work below37another command and store its own information there without having to be38afraid of messing up the state of the parent command.3940Because the parent data is however available it's possible to navigate to41it if needed.4243Most of the time you don't see the context object, but when writing more44complex applications it comes in handy.  This brings us to the next point.4546Calling Convention47``````````````````4849When a Click command callback is executed it's passed all the non hidden50parameters as keyword arguments.  Notably absent is the context.  However51a callback can opt-into being passed the context object by marking itself52with :func:`pass_context`.5354So how do you invoke a command callback if you don't know if it should55receive the context or not?  The answer is that the context itself56provides a helper function (:meth:`Context.invoke`) which can do this for57you.  It accepts the callback as first argument and then invokes the58function correctly.5960Building a Git61--------------6263In this example we want to build a command line tool that resembles a64version control system a bit.  Systems like git usually provide one65over-arching command that already accepts some parameters and66configuration, and then has extra subcommands that do other things.6768The Root Command69````````````````7071At the top level we need a group that can hold all our commands.  In this72case we use the basic :func:`click.group` which allows us to register73other click commands below it.7475For this command we also want to accept some parameters that configure the76state of our tool:7778.. click:example::7980    import os81    import click828384    class Repo(object):85        def __init__(self, home=None, debug=False):86            self.home = os.path.abspath(home or '.')87            self.debug = debug888990    @click.group()91    @click.option('--repo-home', envvar='REPO_HOME', default='.repo')92    @click.option('--debug/--no-debug', default=False,93                  envvar='REPO_DEBUG')94    @click.pass_context95    def cli(ctx, repo_home, debug):96        ctx.obj = Repo(repo_home, debug)979899So let's understand what this does.  We create a group command which can100have subcommands.  When it is invoked it will create an instance of a101``Repo`` class.  This holds the state for our command line tool.  In this102case it just remembers some parameters but at this point it could also103start loading config files and so on.104105This state object is then remembered as :attr:`~Context.obj` on the106context.  This is a special attribute where commands are supposed to107remember what they need to pass on to their children.108109In order for this to work we need to mark our function with110:func:`pass_context` because otherwise the context object would be111entirely hidden from us.112113The First Child Command114```````````````````````115116So let's add our first child command to it.  Let's go with the clone117command:118119.. click:example::120121    @cli.command()122    @click.argument('src')123    @click.argument('dest', required=False)124    def clone(src, dest):125        pass126127So now we have a clone command, but how do we get access to the repo?  As128you can imagine one way is to use the :func:`pass_context` function which129again will make our callback also get the context passed on which we130memorized the repo.  Even better there is a second version of this131decorator called :func:`pass_obj` which will just pass the stored object,132in our case the repo:133134.. click:example::135136    @cli.command()137    @click.argument('src')138    @click.argument('dest', required=False)139    @click.pass_obj140    def clone(repo, src, dest):141        pass142143Interleaved Commands144````````````````````145146While not relevant for this particular program we want to build there is147also quite good support for interleaving systems.  Imagine for instance148there would be this super cool plugin for our version control system that149needs a lot of configuration and wants to store its own configuration as150:attr:`~Context.obj`.  If we would then attach another command below that,151all the sudden we would get the plugin config instead of our repo object.152153One obvious way is to store a reference to the repo on the plugin but then154a command needs to be aware that it's attached below such a plugin.155156There is a much better system by taking advantage of the linked nature of157contexts.  We know that the plugin context is linked to the context that158created our repo.  Because of that we can start a search for the last159level where the object stored on the context was a repo.160161Built-in support for this is provided by the :func:`make_pass_decorator`162factory which will create decorators for us that find objects (it163internally calls into :meth:`Context.find_object`).  So in our case we164know that we want to find the closest ``Repo`` object.  So let's make a165decorator for this:166167.. click:example::168169    pass_repo = click.make_pass_decorator(Repo)170171If we now use ``pass_repo`` instead of ``pass_obj`` we will always get a172repo instead of something else:173174.. click:example::175176    @cli.command()177    @click.argument('src')178    @click.argument('dest', required=False)179    @pass_repo180    def clone(repo, src, dest):181        pass182183Ensuring Objects184````````````````185186The above example only works if there was an outer command that created a187``Repo`` object and stored it on the context.  For some more advanced use188cases this might be a problem for you.  The default behavior of189:func:`make_pass_decorator` is to call into :meth:`Context.find_object`190which will find the object.  If it can't find the object it will raise an191error.  The alternative behavior is to use :meth:`Context.ensure_object`192which will find the object, or if it cannot find it, will create one and193store it on the innermost context.  This behavior can also be enabled for194:func:`make_pass_decorator` by passing ``ensure=True``:195196.. click:example::197198    pass_repo = click.make_pass_decorator(Repo, ensure=True)199200In this case the innermost context gets such an object created if it's201missing.  This might replace objects being placed there earlier.  In this202case the command stays executable, even if the outer command does not run.203For this to work the object type needs to have a constructor that accepts204no arguments.205206As such it runs standalone:207208.. click:example::209210    @click.command()211    @pass_repo212    def cp(repo):213        click.echo(repo)214215As you can see:216217.. click:run::218219    invoke(cp, [])