我有使用api密钥身份验证的tastypie api。
它为GET请求双向工作,但是对于发布请求,它不起作用。
url = http://localhost:8000/api/path/?api_key=key&username=username
在视图中,当我尝试打印request.user时,当邮递员提出请求时,它是普通用户/真实用户。但是对于python请求,它是匿名用户。
使用python请求,我这样做:
url = http://localhost:8000/api/path/?api_key=key&username=username
d = {"some": "data"}
r = requests.post(url, data=json.dumps(d), headers={"content-type": "application/json"})
邮递员提供的代码:
POST /api/v1/abc/?api_key=somekey&username=something HTTP/1.1
Host: localhost:8000
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: something
{"something":"something"}
如有任何问题,请与我们联系。
我的资源api身份验证不起作用:
class UserResource(ModelResource):
class Meta:
queryset = User.objects.all()
fields = ['username', 'email', 'first_name', 'last_name']
resource_name = 'user'
authentication = ApiKeyAuthentication()
答案 0 :(得分:1)
确保您的身份验证中未使用SessionAuthentication
或启用enforce_csrf
。由于邮递员也发送了带有请求的浏览器cookie,这可能是您获得不同行为的原因。
如果是这种情况,则表示API身份验证无效。由于postman正在使用SessionAuthentication,因此它可以工作。确保您已在INSTALLED_APPS中添加了tastypie并在数据库中创建/存储了api密钥。