Debian Codegraph @

third_party/python/aiohttp/examples/cli_app.py

raw
1 #!/usr/bin/env python3
2 """
3 Example of serving an Application using the `aiohttp.web` CLI.
4
5 Serve this app using::
6
7 $ python -m aiohttp.web -H localhost -P 8080 --repeat 10 cli_app:init \
8 > "Hello World"
9
10 Here ``--repeat`` & ``"Hello World"`` are application specific command-line
11 arguments. `aiohttp.web` only parses & consumes the command-line arguments it
12 needs (i.e. ``-H``, ``-P`` & ``entry-func``) and passes on any additional
13 arguments to the `cli_app:init` function for processing.
14 """
15
16 from argparse import ArgumentParser, Namespace
17
18 from aiohttp import web
19
20 args_key = web.AppKey("args_key", Namespace)
21
22
23 async def display_message(req: web.Request) -> web.StreamResponse:
24 args = req.app[args_key]
25 text = "\n".join([args.message] * args.repeat)
26 return web.Response(text=text)
27
28
29 def init(argv):
30 arg_parser = ArgumentParser(
31 prog="aiohttp.web ...", description="Application CLI", add_help=False
32 )
33
34 # Positional argument
35 arg_parser.add_argument("message", help="message to print")
36
37 # Optional argument
38 arg_parser.add_argument(
39 "--repeat", help="number of times to repeat message", type=int, default="1"
40 )
41
42 # Avoid conflict with -h from `aiohttp.web` CLI parser
43 arg_parser.add_argument(
44 "--app-help", help="show this message and exit", action="help"
45 )
46
47 args = arg_parser.parse_args(argv)
48
49 app = web.Application()
50 app[args_key] = args
51 app.router.add_get("/", display_message)
52
53 return app