Manage your keys

Recommendations to manage your api keys

Don't hardcode your keys

It is very inadvisable to hardcode your api keys in your application code. These keys are confidential information that allow you to use your account, you must not share them. I recommend that you use a configuration because it will allow you to share your program without risking to compromise your account.

How to properly use a configuration?

Using a configuration allows you to share your code without having to change it first, but it could be annoying if you need to change your configuration before you share it. I advise you to use a template and copy it automatically when there is no config. You can use various configuration formats, I love toml, yaml is fine, json works.

Example using toml

Code

class Config:
    def __init__(self, file_name, template_name):
        config_file = self.extract_config(file_name, template_name)
        self.load_config(config_file)

    def get_path(self, name):
        return os.path.join(os.path.dirname(os.path.realpath(__file__)), name)

    def extract_config(self, file_name, template_name):
        config_file = self.get_path(file_name)
        if not os.path.isfile(config_file):
            print("config file doesn't exist, copying template!")
            shutil.copyfile(self.get_path(template_name), config_file)
        return config_file

    def load_config(self, config_file):
        config = toml.load(config_file)

        binance = config["binance"]
        self.api_key = binance["api_key"]
        self.api_secret = binance["api_secret"]

config = Config("config.toml", "config.template.toml")
client = binance.Client(config.api_key, config.api_secret)

Config

[binance]
api_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
api_secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

Last updated