【问题标题】:How to use requests to send a PATCH request with headers如何使用请求发送带有标头的 PATCH 请求
【发布时间】:2016-10-25 21:44:50
【问题描述】:

我有一个 Rails 4 应用程序,它使用基于令牌的 API 身份验证,需要能够通过 Python 3 脚本更新记录。

我当前的脚本是这样的

import requests
import json

url = 'http://0.0.0.0:3000/api/v1/update_experiment.json'
payload = {'expt_name' : 'A60E001', 'status' : 'done' }

r = requests.patch(url, payload)

如果我禁用 API 身份验证,它可以正常工作。

我不知道如何向它添加标题,requests.patch 根据文档只需要两个参数。

我需要达到添加以下标题信息的地步

'Authorization:Token token="xxxxxxxxxxxxxxxxxxxxxx"'

这种类型的标题在 curl 中可以正常工作。如何在 Python 3 和请求中做到这一点?

【问题讨论】:

  • 您是否真的尝试添加headers=?发生了什么?
  • 我厌倦了headers= {'Authorization': 'Token', 'token': 'xxxxxx' } 然后r = requests.patch(url, payload, headers=headers) 之类的东西,但什么也没发生,Python 没有错误,WebRick 在 Rails 方面没有反应。尝试使用日志看看发生了什么。

标签: python python-3.x python-requests


【解决方案1】:

patch 接受 kwargs,只需传递 headers = {your_header}:

def patch(url, data=None, **kwargs):
    """Sends a PATCH request.

    :param url: URL for the new :class:`Request` object.
    :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response <Response>` object
    :rtype: requests.Response
    """

    return request('patch', url,  data=data, **kwargs)

有点像:

head = {"Authorization":"Token token=xxxxxxxxxxxxxxxxxxxxxx"}
url = 'http://0.0.0.0:3000/api/v1/update_experiment.json'
payload = {'expt_name' : 'A60E001', 'status' : 'done' }

r = requests.patch(url, payload, headers=head)

【讨论】:

  • 嗨。我试过headers= {'Authorization': 'Token', 'token': 'xxxxxx' } 然后r = requests.patch(url, payload, headers=headers) 但Rails 似乎不喜欢这个。身份验证失败。如何查看 Python 实际发送的内容,如何检查标头。我绑定了print(r.headers),但这不包括我作为标题传入的任何信息。
  • @BartC 请注意,这不是标题的格式 - 重新阅读最后一个代码 sn-p。
  • @PadraicCunningham 非常感谢!!!!,效果很好,错过了那个细节/只是没有得到它,这一直是我其他许多尝试使它工作的罪魁祸首。再次感谢。
猜你喜欢
  • 1970-01-01
  • 2011-10-01
  • 1970-01-01
  • 2013-10-16
  • 1970-01-01
  • 2016-11-10
  • 2011-09-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多