Using reverse URL in Django-tastypie with names will ease our development or making unit test. When I wrote this, I was helped by Joshbohde from Django-tastypie IRC. So, if you have some problem when using Tastypie, I suggest you ask to via IRC.
I have APP/insurance here for example. By default, I can access Django-Tastypie Resource API with reverse(), eg :
1 2 3 | from django.core.urlresolvers import reverse url = reverse(‘api_dispatch_list’, kwargs={‘resource_name’: ‘insurance’}) |
I thinks it’s too long here. Then, we can use “names” django url feature. Now, let we define our api.py, eg :
api.py :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | from card.models import Card from tastypie.resources import ModelResource from django.conf.urls.defaults import url from tastypie import http class InsuranceResource(ModelResource): """Insurance resources to manage API Call.""" class Meta: resource_name = ‘card’ allowed_methods = [‘get’,] # Only GET method allowed here def override_urls(self): """Create custom API URL (eg. file extension, url path ) For reverse urls purpose, we remove (?P<resource_name>) Usage : reverse(‘api_insurance_all’) for list all record """ return [ url(r"^%s/all$" % self._meta.resource_name, self.wrap_view(‘dispatch_list’), name="api_insurance_all"), url(r"^%s/schema$" % self._meta.resource_name, self.wrap_view(‘get_schema’), name="api_insurance_schema"), url(r"^%s/get/(?P<pk>w[w/-]*)$" % self._meta.resource_name, self.wrap_view(‘dispatch_detail’), name="api_insurance_get"), ] |
You can see that I define custom names for api_dispatch_list as “api_insurance_all”. What I expect here, I can access this API simply as “reverse(‘names’)” , for instance:
1 | reverse(‘api_insurance_all’) |
Then, we should include this override_urls() into PROJECT/urls.py
urls.py :
1 2 3 4 5 6 7 8 9 10 11 | from django.conf.urls.defaults import patterns, include from insurance.api import InsuranceResource # load InsuranceResource from insurance/api.py insurance_resource = InsuranceResource() urlpatterns = patterns(”, …. # Including insurance resource API urls (r’^api/’, include(insurance_resource.urls)), ) |
Now we already setup Django-tastypie custom URLS Names. If you want to test from unittesting, then you can do like this :
1 2 3 4 5 6 7 8 9 10 | class ApiInsuranceTestCase(TestCase): def test_all_request(self): resp = self.client.get(reverse(‘api_insurance_all’), data={‘format’: ‘json’}, **self.auth_headers) def test_get_details(self): insurer_id = ’17’ resp = self.client.get(reverse(‘api_insurance_get’, kwargs={‘pk’: insurer_id}), data={‘format’: ‘json’}, **self.auth_headers) |