django-orchestra/orchestra/api/root.py

71 lines
2.5 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
2014-11-14 15:51:18 +00:00
from ..core import services, accounts
2014-05-13 13:47:06 +00:00
class APIRoot(views.APIView):
names = (
'ORCHESTRA_SITE_NAME',
'ORCHESTRA_SITE_VERBOSE_NAME'
)
2014-05-13 13:47:06 +00:00
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'),
]
2014-11-14 15:51:18 +00:00
body = {
2015-02-24 09:34:26 +00:00
'accountancy': {},
'services': {},
2014-11-14 15:51:18 +00:00
}
2014-05-13 13:47:06 +00:00
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-11-14 15:51:18 +00:00
model = viewset.model
group = None
if model in services:
group = 'services'
menu = services[model].menu
2014-11-18 13:59:21 +00:00
if model in accounts:
2014-11-14 15:51:18 +00:00
group = 'accountancy'
menu = accounts[model].menu
if group and menu:
2015-02-24 09:34:26 +00:00
body[group][basename] = {
2014-11-14 15:51:18 +00:00
'url': url,
'verbose_name': model._meta.verbose_name,
'verbose_name_plural': model._meta.verbose_name_plural,
2015-02-24 09:34:26 +00:00
}
2014-09-30 16:39:47 +00:00
headers = {
'Link': ', '.join(links)
}
2014-11-14 15:51:18 +00:00
body.update({
name.lower(): getattr(settings, name, None)
for name in self.names
})
2014-05-13 13:47:06 +00:00
return Response(body, headers=headers)
def metadata(self, request):
ret = super(APIRoot, self).metadata(request)
ret['settings'] = {
2014-11-14 15:51:18 +00:00
name.lower(): getattr(settings, name, None)
for name in self.names
2014-05-13 13:47:06 +00:00
}
return ret