Skip to content

Instantly share code, notes, and snippets.

@thehungrycoder
Last active December 11, 2015 23:58
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 thehungrycoder/4680462 to your computer and use it in GitHub Desktop.
Save thehungrycoder/4680462 to your computer and use it in GitHub Desktop.
Overriding Resource class to use custom data source in tastypie
from tastypie.resources import Resource
from tastypie import fields
class dict2obj(object):
"""
Convert dictionary to object
@source http://stackoverflow.com/a/1305561/383912
"""
def __init__(self, d):
self.__dict__['d'] = d
def __getattr__(self, key):
value = self.__dict__['d'][key]
if type(value) == type({}):
return dict2obj(value)
return value
class BlogResource(Resource):
title = fields.CharField(attribute='title')
content = fields.CharField(attribute='content')
author = fields.CharField(attribute='author_name')
class Meta:
resource_name = 'blogs'
def obj_get_list(self, request=None, **kwargs):
posts = []
#your actual logic to retrieve contents from external source.
#example
posts.append(dict2obj(
{
'title': 'Test Blog Title 1',
'content': 'Blog Content',
'author_name': 'User 1'
}
))
posts.append(dict2obj(
{
'title': 'Test Blog Title 2',
'content': 'Blog Content 2',
'author_name': 'User 2'
}
))
return posts
@srkama
Copy link

srkama commented May 8, 2015

To support recent versions of tastypie...

#initialize d with None
def init(self, d=None):
self.dict['d'] = d

#add object_class in Meta description
class Meta:
resource_name = 'blogs'
object_class = 'dict2obj

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment