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 fileTake it
The walk stopped after 200 commits: lines older than 09d219d point at it.
Added travis configArmin Ronacherbefore adoption09d219d
lines 1–7why, one step back1.. _complex-guide:23Complex Applications4====================56.. currentmodule:: click7Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
lines 8–12why, one step back8Click 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 needAdded travis configArmin Ronacherbefore adoption09d219d
lines 13–14why, one step back13to interact with each other and be cross configured.14Merge pull request #63 from julen/doc-fixesArmin Ronacherbefore adoption0868754
line 15why, one step back15In a theoretical world of two separate click command line utilities theyMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 16why, one step back16can solve this problem by nesting one inside the other. For instance, theAdded travis configArmin Ronacherbefore adoption09d219d
lines 17–28why, one step back17web 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````````28Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
lines 29–33why, one step back29Whenever 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.Added travis configArmin Ronacherbefore adoption09d219d
lines 34–39why, one step back3435Context 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.39Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 40why, one step back40Because the parent data is available, however, it is possible to navigate toAdded travis configArmin Ronacherbefore adoption09d219d
lines 41–48why, one step back41it 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``````````````````48Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
lines 49–51why, one step back49When 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 itselfAdded travis configArmin Ronacherbefore adoption09d219d
lines 52–59why, one step back52with :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.59Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
lines 60–61why, one step back60Building a Git Clone61--------------------Added travis configArmin Ronacherbefore adoption09d219d
lines 62–63why, one step back6263In this example we want to build a command line tool that resembles aMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 64why, one step back64version control system. Systems like Git usually provide oneAdded travis configArmin Ronacherbefore adoption09d219d
line 65why, one step back65over-arching command that already accepts some parameters andMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 66why, one step back66configuration, and then have extra subcommands that do other things.Added travis configArmin Ronacherbefore adoption09d219d
lines 67–70why, one step back6768The Root Command69````````````````70Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
lines 71–72why, one step back71At 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 registerAdded travis configArmin Ronacherbefore adoption09d219d
lines 73–101why, one step back73other 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 thisMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
lines 102–103why, one step back102case it just remembers some parameters, but at this point it could also103start loading configuration files and so on.Added travis configArmin Ronacherbefore adoption09d219d
lines 104–108why, one step back104105This 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.108Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
lines 109–110why, one step back109In order for this to work, we need to mark our function with110:func:`pass_context`, because otherwise the context object would beAdded travis configArmin Ronacherbefore adoption09d219d
lines 111–115why, one step back111entirely hidden from us.112113The First Child Command114```````````````````````115Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 116why, one step back116Let's add our first child command to it, the clone command:Added travis configArmin Ronacherbefore adoption09d219d
lines 117–126why, one step back117118.. 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? AsMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 127why, one step back127you can imagine, one way is to use the :func:`pass_context` function whichAdded travis configArmin Ronacherbefore adoption09d219d
line 128why, one step back128again will make our callback also get the context passed on which weMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
lines 129–131why, one step back129memorized 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):Added travis configArmin Ronacherbefore adoption09d219d
lines 132–144why, one step back132133.. 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````````````````````144Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
lines 145–146why, one step back145While not relevant for the particular program we want to build, there is146also quite good support for interleaving systems. Imagine for instance thatAdded travis configArmin Ronacherbefore adoption09d219d
lines 147–149why, one step back147there 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,Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
lines 150–151why, one step back150we would all of a sudden get the plugin configuration instead of our repo151object.Added travis configArmin Ronacherbefore adoption09d219d
line 152why, one step back152Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
lines 153–155why, one step back153One 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.Added travis configArmin Ronacherbefore adoption09d219d
line 156why, one step back156Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
lines 157–159why, one step back157There 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 lastAdded travis configArmin Ronacherbefore adoption09d219d
lines 160–162why, one step back160level where the object stored on the context was a repo.161162Built-in support for this is provided by the :func:`make_pass_decorator`Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
lines 163–165why, one step back163factory, 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 aAdded travis configArmin Ronacherbefore adoption09d219d
lines 166–171why, one step back166decorator for this:167168.. click:example::169170 pass_repo = click.make_pass_decorator(Repo)171Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 172why, one step back172If we now use ``pass_repo`` instead of ``pass_obj``, we will always get aAdded travis configArmin Ronacherbefore adoption09d219d
lines 173–183why, one step back173repo 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 pass183Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
lines 184–185why, one step back184Ensuring Object Creation185````````````````````````Added travis configArmin Ronacherbefore adoption09d219d
lines 186–188why, one step back186187The 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 useMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
lines 189–191why, one step back189cases, 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 anAdded travis configArmin Ronacherbefore adoption09d219d
line 192why, one step back192error. The alternative behavior is to use :meth:`Context.ensure_object`Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 193why, one step back193which will find the object, and if it cannot find it, will create one andAdded travis configArmin Ronacherbefore adoption09d219d
lines 194–200why, one step back194store 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)200Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 201why, one step back201In this case, the innermost context gets an object created if it isAdded travis configArmin Ronacherbefore adoption09d219d
line 202why, one step back202missing. This might replace objects being placed there earlier. In thisMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
lines 203–204why, one step back203case, 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 acceptsAdded travis configArmin Ronacherbefore adoption09d219d
lines 205–220why, one step back205no 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, [])