djangotastypie

Does Tastypie have a helper function to generate API keys?


What I'm trying to do is whenever the user requests an API key--regardless of whether the user already generated one or not--the system will generate an entirely new key.

I know that whenever calling ApiKey.objects.create() will generate an API key for the user that doesn't have one generated. However, if a user does have one, then trying to call the .create() method throws an error.

In this case, I figured that it would be best to write my own key generator. However, I am now hoping that maybe someone here might know of a helper function that will allow me to generate a random API key, and then let me save it to the database manually myself.

Would anyone might know of any such a helper function?


Solution

  • I figured it out.

    First, you make an attempt to get the the user's API key. If it exists, then there will be no error thrown. To regenerate, set the value of the retrieved user's key to None, and then save the key.

    If there was an error thrown, then simply create a new key.

    try:
        api_key = ApiKey.objects.get(user=someuser)
        api_key.key = None
        api_key.save()
    
    except ApiKey.DoesNotExist:
        api_key = ApiKey.objects.create(user=someuser)