Tastypie Api Key身份验证不适用于foreman / heroku

时间:2014-07-10 19:14:41

标签: django api curl heroku tastypie

我有一个需要ApiKey身份验证的api。如果我在本地使用manage.py runserver运行这个api它工作得很好但是如果我使用foreman在本地启动并部署到heroku它会出现以下错误

{
"error_message": "'NoneType' object has no attribute 'DoesNotExist'", 
"traceback": "Traceback (most recent call last):\n\n  File \"/Users/carlosbalderas/.virtualenvs/recommenu/lib/python2.7/site-packages/tastypie/resources.py\", line 195, in wrapper\n    response = callback(request, *args, **kwargs)\n\n  File \"/Users/carlosbalderas/.virtualenvs/recommenu/lib/python2.7/site-packages/tastypie/resources.py\", line 435, in dispatch_detail\n    return self.dispatch('detail', request, **kwargs)\n\n  File \"/Users/carlosbalderas/.virtualenvs/recommenu/lib/python2.7/site-packages/tastypie/resources.py\", line 453, in dispatch\n    self.is_authenticated(request)\n\n  File \"/Users/carlosbalderas/.virtualenvs/recommenu/lib/python2.7/site-packages/tastypie/resources.py\", line 536, in is_authenticated\n    auth_result = self._meta.authentication.is_authenticated(request)\n\n  File \"/Users/carlosbalderas/.virtualenvs/recommenu/lib/python2.7/site-packages/tastypie/authentication.py\", line 197, in is_authenticated\n    except (User.DoesNotExist, User.MultipleObjectsReturned):\n\nAttributeError: 'NoneType' object has no attribute 'DoesNotExist'\n"

我正在使用这些卷发与我的api互动 (的runserver)

curl -H "Authorization: ApiKey USERNAME:APIKEY" http://127.0.0.1:8000/api/v1/user/

(工头)

curl -H "Authorization: ApiKey USERNAME:APIKEY" http://0.0.0.0:5000/api/v1/user/

(heroku上)

curl -H "Authorization: ApiKey USERNAME:APIKEY" http://fancy-name.herokuapp.com/api/v1/user/

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我知道这是一个稍微老一点的帖子,但我刚刚找到了解决方案(无论如何)。

解决方案是将API密钥信号(described here)移动到应用程序主目录中的signals.py文件中。

问题是Tastypie通过User.USERNAME_FIELD获取了用户名字段。如果您已创建自定义用户,或者由于某种原因django.contrib.admin.get_user_model方法未正确返回,则tastypie将默认为"无"的用户名字段。

这里是代码(来自tastypie' compat.py):

    try:
        from django.contrib.auth import get_user_model
        User = get_user_model()
        username_field = User.USERNAME_FIELD
    except ImproperlyConfigured:
        # The the users model might not be read yet.
        # This can happen is when setting up the create_api_key signal, in your
        # custom user module.
        User = None
        username_field = None

由于我在models.py文件中设置了api密钥信号,因此get_user_model方法未正确返回,并且tastypie默认为username_field = None。