Skip to content
Myr

complex.rst

This file

Path

docs/complex.rst

220 lines · 7.6 KiB

Last changed by

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

History of this file

Take it

1.. _complex-guide:23Complex Applications4====================56.. currentmodule:: click78Click is designed to assist with the creation of complex and simple CLI tools9alike.  However, the power of its design is the ability to arbitrarily nest10systems together.  For instance, in case you have ever used Django, you will11have realized that it provides a command line utility, but so does Celery (for12instance).  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.  It remembers parsed31parameters, what command created it, which resources need to be cleaned up32at the end of the function, and so forth.  It can also optionally hold an33application-defined object.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 available, however, it is 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.  However,51a 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 Git Clone61--------------------6263In this example we want to build a command line tool that resembles a64version control system.  Systems like Git usually provide one65over-arching command that already accepts some parameters and66configuration, and then have 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 configuration 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```````````````````````115116Let's add our first child command to it, the clone command:117118.. click:example::119120    @cli.command()121    @click.argument('src')122    @click.argument('dest', required=False)123    def clone(src, dest):124        pass125126So now we have a clone command, but how do we get access to the repo?  As127you can imagine, one way is to use the :func:`pass_context` function which128again will make our callback also get the context passed on which we129memorized the repo.  However, there is a second version of this decorator130called :func:`pass_obj` which will just pass the stored object, (in our case131the repo):132133.. click:example::134135    @cli.command()136    @click.argument('src')137    @click.argument('dest', required=False)138    @click.pass_obj139    def clone(repo, src, dest):140        pass141142Interleaved Commands143````````````````````144145While not relevant for the particular program we want to build, there is146also quite good support for interleaving systems.  Imagine for instance that147there would be this super cool plugin for our version control system that148needs a lot of configuration and wants to store its own configuration as149:attr:`~Context.obj`.  If we would then attach another command below that,150we would all of a sudden get the plugin configuration instead of our repo151object.152153One obvious way to remedy this is to store a reference to the repo in the154plugin, but then a command needs to be aware that it's attached below such a155plugin.156157There is a much better system that can built by taking advantage of the linked158nature of contexts.  We know that the plugin context is linked to the context159that created our repo.  Because of that, we can start a search for the last160level where the object stored on the context was a repo.161162Built-in support for this is provided by the :func:`make_pass_decorator`163factory, which will create decorators for us that find objects (it164internally calls into :meth:`Context.find_object`).  In our case, we165know that we want to find the closest ``Repo`` object, so let's make a166decorator for this:167168.. click:example::169170    pass_repo = click.make_pass_decorator(Repo)171172If we now use ``pass_repo`` instead of ``pass_obj``, we will always get a173repo instead of something else:174175.. click:example::176177    @cli.command()178    @click.argument('src')179    @click.argument('dest', required=False)180    @pass_repo181    def clone(repo, src, dest):182        pass183184Ensuring Object Creation185````````````````````````186187The above example only works if there was an outer command that created a188``Repo`` object and stored it on the context.  For some more advanced use189cases, this might become a problem.  The default behavior of190:func:`make_pass_decorator` is to call :meth:`Context.find_object`191which will find the object.  If it can't find the object, it will raise an192error.  The alternative behavior is to use :meth:`Context.ensure_object`193which will find the object, and if it cannot find it, will create one and194store it on the innermost context.  This behavior can also be enabled for195:func:`make_pass_decorator` by passing ``ensure=True``:196197.. click:example::198199    pass_repo = click.make_pass_decorator(Repo, ensure=True)200201In this case, the innermost context gets an object created if it is202missing.  This might replace objects being placed there earlier.  In this203case, the command stays executable, even if the outer command does not run.204For this to work, the object type needs to have a constructor that accepts205no arguments.206207As such it runs standalone:208209.. click:example::210211    @click.command()212    @pass_repo213    def cp(repo):214        click.echo(repo)215216As you can see:217218.. click:run::219220    invoke(cp, [])