【问题标题】:Tastypie api working with postman but not with python requestsTastypie api 与邮递员一起使用,但不适用于 python 请求
【发布时间】:2017-08-21 08:35:32
【问题描述】:

我有带有 api 密钥身份验证的美味派 api。

它对 GET 请求双向工作,但对于 post 请求,它不起作用。

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()

【问题讨论】:

  • 您使用的是哪种身份验证?
  • 它的api密钥认证。
  • 您可以在通过 Postman 发送时添加请求的代码(在您的问题中)吗?代码链接将在保存按钮下方提供。
  • 感谢 Abijith,更新了问题。请检查。
  • 我猜你的 api 密钥有问题!而且您提到的网址与邮递员网址不同!

标签: python django tastypie postman


【解决方案1】:

确保您没有使用SessionAuthentication 或在您的身份验证中启用enforce_csrf。由于邮递员也随请求发送浏览器 cookie,这可能是您得到不同行为的原因。

如果是这种情况,则意味着 API 身份验证不起作用。由于邮递员使用的是 SessionAuthentication,所以它可以工作。确保您已在 INSTALLED_APPS 中添加了美味派,并在数据库中创建/存储了 api 密钥。

【讨论】:

  • 似乎正确,因为我已经看到邮递员正在设置 cookie(我在服务器日志中看到)。但我正在使用身份验证 = ApiKeyAuthentication()。此外,我们在同一台服务器上有网站和 api,所以我们使用会话身份验证。但是对于单个 api,我们有 apikeyauthentication。解决办法是什么?
  • 很可能您提供身份验证凭据的方式不正确。尝试解决这个问题
  • 完成,请检查更新的问题。我添加了我的资源。
  • 确保您已在 INSTALLED_APPS 中添加了 sweetpie 并在数据库中创建/存储了 api 密钥。
猜你喜欢
  • 2019-07-03
  • 1970-01-01
  • 2020-11-08
  • 2021-10-06
  • 2023-03-30
  • 2019-08-28
  • 2019-08-25
  • 2018-03-26
  • 2020-11-20
相关资源
最近更新 更多