I'm using the very good Click framework to build a Python CLI that acts as a "wrapper" around a set of complex REST APIs. I've used the "complex" example in order to have good boilerplate code to build the rest of CLI.
However, since the CLI itself communicates with REST APIs, I need a bit of configuration for each command. Example: user authentication (id, password, etc.), and, if different from the default one, the URL to API server.
I could force the user to put these configuration as parameters for each command, but this would be really annoying when executing many commands (the user has to insert his auth details for every command).
Is there a way to have the user enter his credentials at the first command in order to have his uid/pwd persist for the entire session (like the mysql-cli, for example), and, after executing the commands he needed, "logout" from the CLI?
The way this is normally done is to have a configure
command that stores these credentials in a file (normally in the user's $HOME
folder, if you are on Linux) and changes its permissions so it is only readable by the user.
You can use configparser
(or JSON or YAML or whatever you want) to load different sets of credentials based on a profile:
# $HOME/.your-config-name
[default]
auth-mode=password
username=bsmith
password=abc123
[system1]
auth-mode=oauth
auth-token=abc-123
auth-url=http://system.1/authenticate
[system2]
auth-mode=anonymous
auth-url=http://this-is.system2/start
Then you can use a global argument (say --profile
) to pick which credentials should be used for a given request:
$ your-cli --profile system1 command --for first-system