Skip to content

Instantly share code, notes, and snippets.

@BennettSmith
Created April 11, 2012 21:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BennettSmith/2363035 to your computer and use it in GitHub Desktop.
Save BennettSmith/2363035 to your computer and use it in GitHub Desktop.
Tastypie Experiment
# myapp/api.py
from tastypie.authorization import Authorization
from tastypie.authentication import ApiKeyAuthentication
from django.core.urlresolvers import NoReverseMatch
from django.conf.urls.defaults import url
from django.http import HttpRequest
from tastypie.utils import trailing_slash
from django.contrib.auth.models import User
from django.db import models
from tastypie.models import create_api_key
from tastypie import fields
from tastypie.resources import ModelResource
from myapp.models import Entry
models.signals.post_save.connect(create_api_key, sender=User)
class ApiModelResource(ModelResource):
# All resources have a "resource_uri" field added by tastypie.
def dehydrate_resource_uri(self, bundle):
"""
For the automatically included ``resource_uri`` field, dehydrate
the URI for the given bundle.
Returns empty string if no URI can be generated.
"""
try:
href = bundle.request.build_absolute_uri(self.get_resource_uri(bundle))
href = href + "?" + bundle.request.GET.urlencode()
return dict({"rel": "http://api.seamlessmedical.com/rels/entry", "href": href})
except NotImplementedError:
return ''
except NoReverseMatch:
return ''
class UserResource(ApiModelResource):
class Meta:
queryset = User.objects.all()
resource_name = 'user'
excludes = ['email', 'password', 'is_active', 'is_staff', 'is_superuser']
fields = ['username', 'first_name', 'last_name', 'last_login']
allowed_methods = ['get']
authentication = ApiKeyAuthentication()
authorization = Authorization()
include_resource_uri = True
include_absolute_url = False
class EntryResource(ApiModelResource):
user = fields.ForeignKey(UserResource, 'user')
class Meta:
queryset = Entry.objects.all()
resource_name = 'entry'
authentication = ApiKeyAuthentication()
authorization = Authorization()
include_resource_uri = True
include_absolute_url = False
def dehydrate_user(self, bundle):
"""
For the automatically included ``resource_uri`` field, dehydrate
the URI for the given bundle.
Returns empty string if no URI can be generated.
"""
try:
href = bundle.request.build_absolute_uri(bundle.data['user'])
href = href + "?" + bundle.request.GET.urlencode()
return dict({"rel": "http://api.seamlessmedical.com/rels/user", "href": href})
except NotImplementedError:
return ''
except NoReverseMatch:
return ''
def alter_list_data_to_serialize(self, request, data):
# TODO: Add any additional modifications to the data dictionary
# that need to happen before serialization.
return data
def alter_detail_data_to_serialize(self, request, data):
# TODO: Add any additional modifications to the data dictionary
# that need to happen before serialization.
return data
from tastypie.utils.timezone import now
from django.contrib.auth.models import User
from django.db import models
from django.template.defaultfilters import slugify
class Entry(models.Model):
user = models.ForeignKey(User)
pub_date = models.DateTimeField(default=now)
title = models.CharField(max_length=200)
slug = models.SlugField()
body = models.TextField()
def __unicode__(self):
return self.title
def save(self, *args, **kwargs):
# For automatic slug generation
if not self.slug:
self.slug = slugify(self.title)[:50]
return super(Entry, self).save(*args, **kwargs)
from django.conf.urls.defaults import *
from tastypie.api import Api
from myapp.api import EntryResource, UserResource
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
v1_api = Api(api_name = 'v1')
v1_api.register(UserResource())
v1_api.register(EntryResource())
entry_resource = EntryResource()
urlpatterns = patterns('',
(r'^blog/', include('myapp.urls')),
(r'^api/', include(v1_api.urls)),
# Examples:
# url(r'^$', 'server.views.home', name='home'),
# url(r'^server/', include('server.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment