Last active
December 11, 2015 23:58
-
-
Save thehungrycoder/4680462 to your computer and use it in GitHub Desktop.
Overriding Resource class to use custom data source in tastypie
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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