Willette Lynch Willette Lynch - 1 year ago 54
Python Question

Whats the simplest and safest method to generate a API KEY and SECRET in Python

I need to generate a API key and Secret that would be stored in a Redis server. What would be the best way to generate a key and secret?

I am develop a Django-tastypie framework based app.

Answer Source

EDIT: for a very secure way of generating random number, you should use urandom:

from binascii import hexlify

key = hexlify(os.urandom(lenght))

this will produce bytes, call key.decode() if you need a string

You can just generate keys of your desired length the python way:

import random
import string

def generate_key(length):
    return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(length))

And then you can just call it with your desired length key = generate_key(40).
You can specify what alphabet you want to use, for example using only string.ascii_lowercase for key consisting of only lowercase letters etc.

There is also Model for Api authentication in tastypie, might be worth checking out https://django-tastypie.readthedocs.org/en/latest/authentication.html#apikeyauthentication

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download