xxxxxxxxxx
# views.py
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
class APIKeyAuthentication(BaseAuthentication):
def authenticate(self, request):
api_key = request.headers.get('X-API-KEY')
if not api_key:
raise AuthenticationFailed('API key missing')
try:
key = models.APIKEY.objects.get(public_key=api_key)
return (key.id, None)
except models.APIKEY.DoesNotExist:
raise AuthenticationFailed('Invalid API key')
class OrderViewSet(viewsets.ModelViewSet):
authentication_classes = [APIKeyAuthentication]
queryset = models.Order.objects.filter(is_deleted=False)
serializer_class = serializers.OrderSerializer
xxxxxxxxxx
from myapp.models import BlogPost
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
content_type = ContentType.objects.get_for_model(BlogPost)
permission = Permission.objects.create(
codename='can_publish',
name='Can Publish Posts',
content_type=content_type,
)
xxxxxxxxxx
class USCitizen(models.Model):
# ...
class Meta:
permissions = (
("can_drive", "Can drive"),
("can_vote", "Can vote in elections"),
("can_drink", "Can drink alcohol"),
)