Skip to content

Instantly share code, notes, and snippets.

View bohde's full-sized avatar

Rowan Bohde bohde

View GitHub Profile
from tastypie.authorization import Authorization
from tastypie.resources import ModelResource
class PerUserAuthorization(Authorization):
"""
Restricts creates, updates, and deletes to the current user
"""
def __init__(self, attr):
self.attr = attr
from django.conf import settings
class AbsoluteImageResource(ModelResource):
def dehydrate_image(self, bundle):
return ''.join([settings.STATIC_URL, bundle.data['image']])
curl -H 'Accept: application/json' 'http://localhost:8000/api/v1/types/1/' | curl -H 'Content-Type: application/json' -X POST --data @- "http://localhost:8000/api/v1/types/"
from django.db.models.sql.constants import LOOKUP_SEP
from tastypie.fields import ToOneField
class NestedToOneField(ToOneField):
def dehydrate(self, bundle):
try:
foreign_obj = reduce(lambda obj, attr: getattr(obj, attr), self.attribute.split(LOOKUP_SEP), bundle.obj)
except ObjectDoesNotExist:
foreign_obj = None
if not foreign_obj:
from itertools import takewhile
def combinator_style(xs):
return Combinators(xs).chain().R(
takewhile, lambda x: x < 7
).R(
filter, lambda x: x < 2
).R(
map, lambda x: 4 * x
).value()
from tastypie.fields import ToMany
class HrefToMany(ToMany):
"""Like a normal ToMany, except dehyrates to a link to a filtered collection"""
def uri_template(self):
if not hasattr(self, '_uri_template'):
self._uri_template = self.make_uri_template()
return self._uri_template
# Let's examine a simple imperative script
def imperative(xs):
results = []
for x in xs:
if x > 7:
break
if x < 2:
result = 4 * x
results.append(result)
@bohde
bohde / tags.py
Created January 30, 2012 03:25
Using django-taggit with django-tastypie
from tastypie.fields import ListField
class TaggedResource(ModelResource):
tags = ListField()
class Meta:
queryset = Model.objects.all()
def build_filters(self, filters=None):
if filters is None:
from django import template
from django.conf import settings
import pystache
register = template.Library()
class MustacheNode(template.Node):
def __init__(self, template_path, attr=None):
self.filepath = '%s/%s' % (settings.TEMPLATE_DIRS[0], template_path)
self.attr = attr
class PackageResource(ModelResource):
# Stuff already there
def obj_get(self, request=None, **kwargs):
kwargs.pop("available_options")
return super(PackageResource, self).obj_get(request=request, **kwargs)