14

我正在用 TastyPie 制作一个内部 API。我有

from tastypie.authentication import ApiKeyAuthentication
class MyResource(ModelResource):
  Meta:
    authentication = ApiKeyAuthentication()

禁用 Auth 规则后,我的 API 运行良好。开启它后,无论我尝试什么,我都会收到 401(未经授权)响应。

我敢肯定,一旦您看到它的实际效果,这是非常明显的事情之一,但与此同时,请告知如何提出请求(GET)。

4

1 回答 1

19

将用户名和 api_key 参数添加到您的 GET 变量中。确保您拥有

curl http://localhost:8000/api/v1/books/?username=issackelly\&api_key=123456789adfljafal

设置时请确保遵循文档中的其他说明:

ApiKeyAuthentication

作为需要密码等敏感数据的替代方案,ApiKeyAuthentication 允许您仅收集用户名和机器生成的 api 密钥。Tastypie 附带了一个专门用于此目的的特殊模型,因此您需要确保 sweetpie 位于 INSTALLED_APPS 中。

Tastypie 包含一个信号函数,可用于自动创建 ApiKey 对象。连接起来看起来像:

from django.contrib.auth.models import User
from django.db import models
from tastypie.models import create_api_key

models.signals.post_save.connect(create_api_key, sender=User)
于 2011-10-18T22:05:33.707 回答