PUT方法在django-tastypie中不起作用?

时间:2013-09-04 08:33:41

标签: python django curl tastypie

我是django-tastypie的新手。这是我的api.py代码,

from tastypie.resources import ModelResource
from .models import ListModel


class ListModelResource(ModelResource):

    def determine_format(self, request):
        return 'application/json'

    class Meta:
        allowed_methods = ['get','put']
        queryset = ListModel.objects.all()

这里我使用CURL进行GET:

curl http://127.0.0.1:8000/api/v1/listmodel/1/

OUT: {"completed": false, "id": 1, "resource_uri": "/api/v1/listmodel/1/", "title": "This is test"}

这里我使用CURL进行PUT:

 curl --dump-header - -H "Content-Type: application/json" '{"completed": false, "id": 1, "resource_uri": "/api/v1/listmodel/1/", "title": "This is test"}' http://127.0.0.1:8000/api/v1/listmodel/1/
HTTP/1.0 401 UNAUTHORIZED
Date: Wed, 04 Sep 2013 08:12:53 GMT
Server: WSGIServer/0.1 Python/2.7.2+
Content-Type: text/html; charset=utf-8

为什么我会得到401?

1 个答案:

答案 0 :(得分:2)

根据tastypie tutorial

  

...如果你尝试向资源发送POST / PUT / DELETE,你会发现   你自己得到“401 Unauthorized”错误。为了安全起见,Tastypie发货   与授权类(“你允许做什么”)设置为   ReadOnlyAuthorization。这样可以安全地在网络上公开,但是   阻止我们进行POST / PUT / DELETE。 ..

您可以使用tastypie.authorization.Authorization启用它:

from tastypie.authorization import Authorization
from tastypie.resources import ModelResource
from .models import ListModel

class ListModelResource(ModelResource):
    def determine_format(self, request):
        return 'application/json'

    class Meta:
        allowed_methods = ['get','put']
        queryset = ListModel.objects.all()
        authorization= Authorization() # <---
  

警告

     

这对于开发中的测试非常有用,但非常不安全。   你永远不应该把这样的资源放在互联网上。请   花一些时间查看authentication / authorization课程   可以在Tastypie中找到。