Django Piston - 有一个login_required装饰器吗?如果没有,我们如何提出错误?

时间:2011-02-01 03:19:42

标签: django django-authentication django-piston

我无法弄清楚如何确保用户在Piston中进行身份验证。这是我尝试过的。

  1. Piston中的Login_required装饰。这似乎不起作用,所以我查看并在活塞中找到了身份验证。
  2. HTTPBasicAuthentication似乎记录用户,而不是确保用户is_authenticated。我只想确保在发布数据之前对它们进行身份验证。
  3. 手动编写代码以检查user.is_authenticated。但是当用户未经过身份验证时,如何引发与Piston错误响应一致的错误?
  4. 在此之后,我被困住了。谢谢你的帮助。

    更新:好的,我弄明白了错误部分。至少,我可以手动完成。如果有人想知道,就是这样。

    from piston.utils import rc
    resp = rc.BAD_REQUEST
    resp.write("Need to be logged in yo")
    return resp
    

2 个答案:

答案 0 :(得分:1)

  • 在handlers.py中为您的匿名客户端创建一个单独的处理程序,扩展piston.handler.AnonymousBaseHandler,如同here所述。
  • 使用Resource参数设置您的urls.py中的authentication,例如this question

编辑: 实际上,通过loggin,piston.authentication.HttpBasicAuthentication 中的用户确保用户is_authenticated。试试这个

def read(self, request):
    return {'user': request.user.is_authenticated()}
在您的处理程序中

并使用curl -u user:password <url>对其进行测试 你会得到

{
    "user": true
}

在您的回复正文中。

答案 1 :(得分:0)

您的错误部分有效,但您通过执行错误请求返回400状态代码,返回未经授权的401状态代码会更“RESTful”。

    resp = HttpResponse("Authorization Required")
    resp.status_code = 401 

以下是所有状态代码的列表:http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html