dclient actor command, closes #26

This commit is contained in:
Simon Willison 2024-02-27 21:08:15 -08:00
commit ea3dc64fb9
2 changed files with 81 additions and 1 deletions

View file

@ -130,7 +130,12 @@ def query(url_or_alias, sql, token, verbose):
)
@click.option("--token", "-t", help="API token")
@click.option("--silent", is_flag=True, help="Don't output progress")
@click.option("-v", "--verbose", is_flag=True, help="Verbose output: show HTTP request and response")
@click.option(
"-v",
"--verbose",
is_flag=True,
help="Verbose output: show HTTP request and response",
)
def insert(
url_or_alias,
table,
@ -259,6 +264,41 @@ def insert(
)
@cli.command()
@click.argument("url_or_alias")
@click.option("--token", help="API token")
def actor(url_or_alias, token):
"""
Show the actor represented by an API token
Example usage:
\b
dclient actor https://latest.datasette.io/fixtures
"""
aliases_file = get_config_dir() / "aliases.json"
aliases = _load_aliases(aliases_file)
if url_or_alias in aliases:
url = aliases[url_or_alias]
else:
url = url_or_alias
if not (url.startswith("http://") or url.startswith("https://")):
raise click.ClickException("Invalid URL: " + url)
if token is None:
token = token_for_url(url, _load_auths(get_config_dir() / "auth.json"))
url_bits = url.split("/")
url_bits[-1] = "-/actor.json"
actor_url = "/".join(url_bits)
response = httpx.get(
actor_url, headers={"Authorization": "Bearer {}".format(token)}, timeout=40.0
)
response.raise_for_status()
click.echo(json.dumps(response.json(), indent=4))
@cli.group()
def alias():
"Manage aliases for different instances"

View file

@ -28,7 +28,21 @@ To delete the token for a specific URL, run `auth remove`:
```bash
dclient auth remove https://latest.datasette.io/
```
## Testing a token
The `dclient actor` command can be used to test a token, retrieving the actor that the token represents.
```bash
dclient actor https://latest.datasette.io/content
```
The output looks like this:
```json
{
"actor": {
"id": "root",
"token": "dstok"
}
}
```
## dclient auth --help
<!-- [[[cog
@ -135,3 +149,29 @@ Options:
```
<!-- [[[end]]] -->
## dclient actor --help
<!-- [[[cog
import cog
result = runner.invoke(cli.cli, ["actor", "--help"])
help = result.output.replace("Usage: cli", "Usage: dclient")
cog.out(
"```\n{}\n```".format(help)
)
]]] -->
```
Usage: dclient actor [OPTIONS] URL_OR_ALIAS
Show the actor represented by an API token
Example usage:
dclient actor https://latest.datasette.io/fixtures
Options:
--token TEXT API token
--help Show this message and exit.
```
<!-- [[[end]]] -->