【问题标题】:PUT method not working in django-tastypie?PUT 方法在 django-tastypie 中不起作用?
【发布时间】:2013-09-07 16:12:49
【问题描述】:

我是 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 ?

【问题讨论】:

    标签: python django curl tastypie


    【解决方案1】:

    根据tastypie tutorial

    ...如果您尝试向资源发送 POST/PUT/DELETE,您会发现 自己收到“401 Unauthorized”错误。为了安全,Tastypie 船 授权类(“你可以做什么”)设置为 只读授权。这样可以安全地在网络上公开,但是 阻止我们执行 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 中可用。

    【讨论】:

      猜你喜欢
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-29
      • 1970-01-01
      相关资源
      最近更新 更多