django-orchestra-test/orchestra/api/root.py

47 lines
1.7 KiB
Python
Raw Normal View History

2014-05-13 13:47:06 +00:00
from rest_framework import views
from rest_framework.response import Response
from rest_framework.reverse import reverse
from .. import settings
class APIRoot(views.APIView):
names = ['SITE_NAME', 'SITE_VERBOSE_NAME']
def get(self, request, format=None):
root_url = reverse('api-root', request=request, format=format)
token_url = reverse('api-token-auth', request=request, format=format)
links = [
'<%s>; rel="%s"' % (root_url, 'api-root'),
'<%s>; rel="%s"' % (token_url, 'api-get-auth-token'),
]
if not request.user.is_anonymous():
list_name = '{basename}-list'
detail_name = '{basename}-detail'
for prefix, viewset, basename in self.router.registry:
singleton_pk = getattr(viewset, 'singleton_pk', False)
if singleton_pk:
url_name = detail_name.format(basename=basename)
2014-09-30 16:39:47 +00:00
kwargs = {
'pk': singleton_pk(viewset(), request)
}
2014-05-13 13:47:06 +00:00
else:
url_name = list_name.format(basename=basename)
kwargs = {}
url = reverse(url_name, request=request, format=format, kwargs=kwargs)
links.append('<%s>; rel="%s"' % (url, url_name))
2014-09-30 16:39:47 +00:00
headers = {
'Link': ', '.join(links)
}
2014-05-13 13:47:06 +00:00
body = {
name.lower(): getattr(settings, name, None) for name in self.names
}
return Response(body, headers=headers)
def metadata(self, request):
ret = super(APIRoot, self).metadata(request)
ret['settings'] = {
name.lower(): getattr(settings, name, None) for name in self.names
}
return ret