Skip to content
Myr

complex.rst

This file

Path

docs/complex.rst

219 lines · 7.5 KiB

Last changed by

Merge pull request #63 from julen/doc-fixesArmin Ronacherbefore adoption0868754

History of this file

Take it

The walk stopped after 200 commits: lines older than 18fff34 point at it.

Added support for multiple arguments.Armin Ronacherbefore adoption18fff34

lines 1–8why, one step back
1.. _complex-guide:
23Complex Applications4====================56.. currentmodule:: click78Click is designed to write complex and simple CLI tools alike. However

Merge pull request #21 from julen/doc-fixesArmin Ronacherbefore adoptiona4b7d70

line 9why, one step back
9the power of its design is the ability to arbitrarily nest systems

Added support for multiple arguments.Armin Ronacherbefore adoption18fff34

lines 10–14why, one step back
10together. For instance in case you have ever used Django you will have
11realized 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.14

Merge pull request #63 from julen/doc-fixesArmin Ronacherbefore adoption0868754

line 15why, one step back
15In a theoretical world of two separate click command line utilities they

Added support for multiple arguments.Armin Ronacherbefore adoption18fff34

lines 16–28why, one step back
16can solve this problem by nesting one inside the other. For instance the
17web 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````````28

Merge pull request #63 from julen/doc-fixesArmin Ronacherbefore adoption0868754

line 29why, one step back
29Whenever a click command is executed a :class:`Context` object is created

Added support for multiple arguments.Armin Ronacherbefore adoption18fff34

lines 30–36why, one step back
30which holds state for this particular invocation. For instance it
31remembers 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 below

Merge pull request #21 from julen/doc-fixesArmin Ronacherbefore adoptiona4b7d70

line 37why, one step back
37another command and store its own information there without having to be

Added support for multiple arguments.Armin Ronacherbefore adoption18fff34

lines 38–43why, one step back
38afraid 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 more

Merge pull request #21 from julen/doc-fixesArmin Ronacherbefore adoptiona4b7d70

line 44why, one step back
44complex applications it comes in handy. This brings us to the next point.

Added support for multiple arguments.Armin Ronacherbefore adoption18fff34

lines 45–48why, one step back
45
46Calling Convention47``````````````````48

Merge pull request #63 from julen/doc-fixesArmin Ronacherbefore adoption0868754

line 49why, one step back
49When a click command callback is executed it's passed all the non hidden

Added support for multiple arguments.Armin Ronacherbefore adoption18fff34

lines 50–70why, one step back
50parameters 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 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````````````````70

Merge pull request #21 from julen/doc-fixesArmin Ronacherbefore adoptiona4b7d70

line 71why, one step back
71At the top level we need a group that can hold all our commands. In this

Added support for multiple arguments.Armin Ronacherbefore adoption18fff34

lines 72–75why, one step back
72case we use the basic :func:`click.group` which allows us to register
73other click commands below it.7475For this command we also want to accept some parameters that configure the

More automated docsArmin Ronacherbefore adoption8254b79

line 76why, one step back
76state of our tool:

Added support for multiple arguments.Armin Ronacherbefore adoption18fff34

line 77why, one step back
77

More automated docsArmin Ronacherbefore adoption8254b79

lines 78–79why, one step back
78.. click:example::
79

Added support for multiple arguments.Armin Ronacherbefore adoption18fff34

lines 80–84why, one step back
80 import os
81 import click828384 class Repo(object):

Added support for object ensuringArmin Ronacherbefore adoption8512acd

lines 85–86why, one step back
85 def __init__(self, home=None, debug=False):
86 self.home = os.path.abspath(home or '.')

Added support for multiple arguments.Armin Ronacherbefore adoption18fff34

lines 87–116why, one step back
87 self.debug = debug
888990 @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 clone

More automated docsArmin Ronacherbefore adoption8254b79

line 117why, one step back
117command:

Added support for multiple arguments.Armin Ronacherbefore adoption18fff34

line 118why, one step back
118

More automated docsArmin Ronacherbefore adoption8254b79

lines 119–120why, one step back
119.. click:example::
120

Added support for multiple arguments.Armin Ronacherbefore adoption18fff34

lines 121–131why, one step back
121 @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,

More automated docsArmin Ronacherbefore adoption8254b79

line 132why, one step back
132in our case the repo:

Added support for multiple arguments.Armin Ronacherbefore adoption18fff34

line 133why, one step back
133

More automated docsArmin Ronacherbefore adoption8254b79

lines 134–135why, one step back
134.. click:example::
135

Added support for multiple arguments.Armin Ronacherbefore adoption18fff34

lines 136–148why, one step back
136 @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 that

Merge pull request #21 from julen/doc-fixesArmin Ronacherbefore adoptiona4b7d70

line 149why, one step back
149needs a lot of configuration and wants to store its own configuration as

Added support for multiple arguments.Armin Ronacherbefore adoption18fff34

lines 150–161why, one step back
150: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`

Added support for object ensuringArmin Ronacherbefore adoption8512acd

lines 162–165why, one step back
162factory which will create decorators for us that find objects (it
163internally 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:

Added support for multiple arguments.Armin Ronacherbefore adoption18fff34

line 166why, one step back
166

More automated docsArmin Ronacherbefore adoption8254b79

lines 167–168why, one step back
167.. click:example::
168

Added support for multiple arguments.Armin Ronacherbefore adoption18fff34

lines 169–171why, one step back
169 pass_repo = click.make_pass_decorator(Repo)
170171If we now use ``pass_repo`` instead of ``pass_obj`` we will always get a

More automated docsArmin Ronacherbefore adoption8254b79

lines 172–174why, one step back
172repo instead of something else:
173174.. click:example::

Added support for multiple arguments.Armin Ronacherbefore adoption18fff34

lines 175–181why, one step back
175
176 @cli.command()177 @click.argument('src')178 @click.argument('dest', required=False)179 @pass_repo180 def clone(repo, src, dest):181 pass

Added support for object ensuringArmin Ronacherbefore adoption8512acd

lines 182–219why, one step back
182
183Ensuring 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, [])