【问题标题】:How to make VIEW returns serialized data?如何让VIEW返回序列化数据?
【发布时间】:2012-03-04 10:42:13
【问题描述】:

URL 在下面的例子中被覆盖了,所以我可以传递类似的东西 http://localhost:8000/api/v1/entry/1234/1233/?format=json,这样做会将参数传递给 WRAP VIEW,当我执行 self.create_response(request, data) 时,浏览器只显示类似

0x2e27a50 处的 api.Entry 对象

在浏览器中,字段不会被序列化: 注意:在这个阶段我不需要 ModelResource。如何使自定义视图 dispatch_data 返回 obj_get 和 get_object_list 之类的数据?以下是有问题的一段代码:

#Object class
Class Entry(object)
    name = ''


#Resource class
class EntryResource(Resource):
    name = fields.CharField(attribute = 'name')

    class Meta:
        resource_name = 'entry'
        object_class = Entry
        include_resource_uri = False 
        authentication = Authentication()
        authorization = Authorization()
        serializer = Serializer()

    def override_urls(self):
        return [url(r"^(?P<resource_name>%s)/(?P<p1>[\d]{4})/(?P<p2>[\d]{4})%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('dispatch_data'),name='api_dispatch_data'),]

    def dispatch_data(self, request, **kwargs):
         p1 = kwargs['p1'] #params can be retrieved here
         p1 = kwargs['p2']
         info = Entry()
         info.name = p1 #just example
         response = {1:info}
         return info.values() 
         #Above results in ERROR, it will say Entry object has no attribute 'has_header' 
         #changing to self.create_response(request, info) will not serialize the fields



#urls.py
api = Api(api_name='v1')
api.register(EntryResource())

urlpatterns = patterns('',
    url(r'^api/', include(api.urls)),
)

【问题讨论】:

    标签: django tastypie


    【解决方案1】:

    我认为 Tastypie 的 Using Tastypie With Non-ORM Data Sources 拥有您需要的所有信息。

    基本上,您应该实现负责返回对象(和/或创建、删除等...如果您需要它们)的方法。除非您需要自定义它的功能,否则您无需触摸“dispatch()”。

    这取决于您的需求,但如果您希望资源的行为就像它具有 obj_get 和 obj_get_list 一样,您需要实现这两者。我提到的例子非常好,应该让你继续......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-03
      • 1970-01-01
      • 2021-12-23
      • 2019-11-30
      • 2020-02-11
      • 1970-01-01
      相关资源
      最近更新 更多