如何使用ApiKeyAuthentication在Django TastyPie中发布请求

时间:2016-10-12 13:44:35

标签: python django tastypie

我有这样的资源:

class EntryResource(ModelResource):
    class Meta:
        queryset = Entry.objects.all()
        resource_name = 'entry'
        allowed_methods = ['post']
        authentication = ApiKeyAuthentication()
        authorization = Authorization()

并根据documentation尝试向此资源发出请求:

requests.post('http://localhost/api/entry/',
              json={"key1": "value1",
                    "key2": "value2"},
              headers={"content-type": "application/json",
                       "Authorization": "ApiKey",
                       "<username>": "<api_key>"})

但得到401。

1 个答案:

答案 0 :(得分:1)

来自文档:

  

授权:A​​piKey daniel:204db7bcfafb2deb7506b89eb3b9b715b09905c8

您的请求必须如下:

requests.post('http://localhost/api/entry/',
              json={"key1": "value1",
                    "key2": "value2"},
              headers={"content-type": "application/json",
                       "Authorization": "ApiKey <username>:<api_key>"})