【问题标题】:How to add headers to slumber in python?如何在python中添加标题以休眠?
【发布时间】:2015-11-13 21:30:14
【问题描述】:

我正在尝试向 parse.com 的 REST API 发送请求。根据 parse 的文档,我需要将 App ID 和 API Key 放在请求中。

我尝试使用 slumber 来做到这一点,但我不断收到 客户端错误 401:http://api.parse.com/1/installations/

将标题添加到休眠的正确方法是什么?我尝试关注文档http://slumber.readthedocs.org/en/latest/options.html#custom-session-objects,但它似乎已经过时,即使经过一些修改,它仍然无法正常工作。

供参考,这是我的代码:

session = requests.Session()
session.headers = {"X-Parse-Application-Id": APPLICATION_ID, "X-Parse-REST-API-Key": API_KEY}

api = slumber.API("http://api.parse.com/1/", session=session)
api.installations.get()

编辑: 而不是 X-Parse-REST-API-Key,它实际上是 X-Parse-Master-Key

【问题讨论】:

    标签: python django session parse-platform push-notification


    【解决方案1】:

    我认为最好的方法是使用自定义身份验证类http://slumber.readthedocs.org/en/latest/options.html#specify-authentication

    import slumber
    from requests.auth import AuthBase
    
    class ParseAuth(AuthBase):
        def __init__(self, app_id, api_key):
            self.app_id = app_id
            self.api_key = api_key
    
        def __call__(self, r):
            r.headers['X-Parse-Application-Id'] = self.app_id
            r.headers['X-Parse-REST-API-Key'] = self.api_key
            return r
    
    api = slumber.API("http://api.parse.com/1/", auth=ParseAuth("my_app_id", "my_api_key"))
    

    【讨论】:

    • 感谢您的回复。我试着按照你说的做,但我仍然得到 401。我确信我的标题应该是正确的,因为它适用于终端中的 curl。我很想知道睡眠是否真的在发送我的标题。有没有办法查看休眠发送的请求内容?
    • nvm 回复。当它应该是https时,我正在使用http。但是,为了调试目的,看看请求是什么样子的还是很不错的。
    • slumber 在后台使用 requests 库,使用它来启用调试日志记录:stackoverflow.com/questions/10588644/…
    猜你喜欢
    • 2011-04-18
    • 1970-01-01
    • 1970-01-01
    • 2011-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多