2

I am building simple app which is using Twitter API. What I have to do to hide my Twitter app keys? For example, if I will put my program to the internet and somebody who look up to the code will know my consumer key, access token etc. And if I not include this information into my program, that it won't be work!

Paweł Kosiński
  • 222
  • 6
  • 14
  • 1
    here is a [similar question](http://stackoverflow.com/questions/5525305/how-to-store-a-secret-api-key-in-an-applications-binary) that you may find useful – Noam Hacker Dec 08 '15 at 20:25

2 Answers2

5

I'm assuming by putting on the internet you mean publishing your code on github or such.

In that case you should always separate code and configuration. Put your API keys in an .ini file, i.e. config.ini, then load that file from python program using configparser

Add configuration file to your .gitignore so it would not get added to the source control.

Alex Volkov
  • 2,812
  • 23
  • 27
4

Assuming you're running on a Unix like system, one way to handle this is environment variables.

In your shell you can do this:

export TWITTER_API_KEY=yoursecretapikey

Note that you don't use quotes of any kind for this.

Then in your script:

import os
twitter_key = os.environ.get('TWITTER_API_KEY')
Josh Rumbut
  • 2,640
  • 2
  • 32
  • 43
  • It works, thanks. But what happened if somebody will download my program and will try to run it? That environment variables will be set in that person OS too? – Paweł Kosiński Dec 08 '15 at 20:28
  • You can check to see if the variable is set using `if "TWITTER_API_KEY" in os.environ`. `os.environ` gets environment variables from any common OS. – Josh Rumbut Dec 08 '15 at 20:41
  • I tried this and it was not retrievable within python and vanished from the unix environment variables after a reboot. – cardamom Mar 22 '17 at 11:44