Skip to content

Instantly share code, notes, and snippets.

@AndrewJHart
Forked from mkubenka/api.py
Last active August 29, 2015 13:56
Show Gist options
  • Save AndrewJHart/9197978 to your computer and use it in GitHub Desktop.
Save AndrewJHart/9197978 to your computer and use it in GitHub Desktop.
Inspiration for the ApiKey resource implementation; thanks to original author martinsandstrom.
from tastypie.exceptions import NotFound
from tastypie.resources import ModelResource
from tastypie.authentication import BasicAuthentication, ApiKeyAuthentication
from tastypie.models import ApiKey, create_api_key
from django.contrib.auth.models import User
# listen for post_save signal on User model & trigger a function to generate the API key
models.signals.post_save.connect(create_api_key, sender=User)
# callable that takes allowed methods for production but returns POST & GET verbs if testing w/ localhost or debug
allowed = lambda methods: ['post', 'get'] if settings.DEBUG and settings.LOCALHOST else methods
class ApiKeyResource(ModelResource):
clasclass Meta:
queryset = ApiKey.objects.all()
resource_name = "api_key"
# security & auth
fields = ["key"]
authorization = Authorization()
authentication = MultiAuthentication(SessionAuthentication(), BasicAuthentication())
# allowed request types
list_allowed_methods = allowed([])
detail_allowed_methods = ["get"]
include_resource_uri = False
def get_detail(self, request, **kwargs):
if kwargs["pk"] != "auth":
# only allow GET for detail view if route matches <resource>/auth/
raise NotImplementedError("Resource not found")
obj = ApiKey.objects.get(user=request.user) # current user
bundle = self.build_bundle(obj=obj, request=request) # create bundle obj
bundle = self.full_dehydrate(bundle) # deserialize fields
bundle = self.alter_detail_data_to_serialize(request, bundle)
# return properly formatted response of current users api key if they're authenticated
return self.create_response(request, bundle)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment