2014-10-02 84 views
0

我有修改基於請求的請求對象中間件如何訪問django-tastypie自定義序列化器中的請求對象?

class MyMiddleware(): 
    def process_request(self, request): 
     if request.path_info = "some special path": 
      request.some_special_attribute = True 
     return request 

我使用自定義序列

class MyResource(ModelResource): 
    name = fields.CharField("name") 
    class Meta: 
     serializer = MySerializer() 


class MySerializer(Serializer): 
    def from_json(self, content): 
     if request.some_special_attribute: 
      # modify the object and return 

和串行必須訪問請求對象的資源返回正確的響應對象

似乎沒有辦法做到這一點。

回答

1

我認爲你會混淆資源的工作和序列化程序的工作。你不應該試圖在你的序列化器中實現任何業務邏輯;它僅用於在json(或其他)和本地python數據結構之間進行轉換。

「並且序列化程序必須訪問請求對象以返回適當的響應對象」。 資源是爲了做到這一點。

我建議您閱讀文檔,瞭解有關保溼和脫水數據的文檔。 http://django-tastypie.readthedocs.org/en/latest/resources.html#advanced-data-preparation

以下是他們根據請求中的屬性更改了請求主體的文檔示例。

class MyResource(ModelResource): 

    class Meta: 
     queryset = User.objects.all() 
     excludes = ['email', 'password', 'is_staff', 'is_superuser'] 

    def dehydrate(self, bundle): 
     # If they're requesting their own record, add in their email address. 
     if bundle.request.user.pk == bundle.obj.pk: 
      # Note that there isn't an ``email`` field on the ``Resource``. 
      # By this time, it doesn't matter, as the built data will no 
      # longer be checked against the fields on the ``Resource``. 
      bundle.data['email'] = bundle.obj.email 
     return bundle 
相關問題