Storing passwords in Jupyter notebooks

2019-07-02 01:53发布

问题:

Is there a way to store secrets/access secrets/passwords in notebooks? I have an api endpoint where I pull data from, and I dont want to expose the apiKey to everyone who can view the notebook.

回答1:

cco's answer is good, but if you're looking for a simpler solution, many people use environmental variables to keep secrets segregated from source code.

For example, you can provide them when executing your script in the shell:

$ API_TOKEN=abc123 python script.py

In your source code:

import os
API_TOKEN = os.environ.get("API_TOKEN")

For your Jupyter notebooks, you can use python-dotenv or a similar package to "retrieve" a .env file that contains your project's secrets and is ignored by your version control system.

Once you've created your .env file (either manually, or using the package's command line tool), you can use python-dotenv in Jupyter (or IPython) like so:

%load_ext dotenv
%dotenv
import os
os.environ.get("API_TOKEN")


回答2:

Store your credentials in a JSON or YAML, and have your notebook parse the necessary parts.

import json

with open('credentials.json') as f:
    data = json.load(f)
    username = data['username']
    password = data['password']

You should avoid printing the secrets in the cell outputs, for otherwise any technique you choose will be foiled.



回答3:

You can use the keyring package to store sensitive information in a system-specific protected store.
It can be installed via pip from pypi.