Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 662
Sal Rahman Avatar asked Jun 07 '12 22:06

Sal Rahman


1 Answers

Based on Filip Dupanović's answer the working code for me was something like this:

user = get_user_model().objects.get(email="[email protected]")
api_key = ApiKey.objects.get_or_create(user=user)
api_key[0].key = api_key[0].generate_key()
api_key[0].save()
like image 79
r.aj Avatar answered Sep 27 '22 23:09

r.aj