【问题标题】:Instagram Signed Call in PythonPython 中的 Instagram 签名调用
【发布时间】:2015-03-26 02:49:00
【问题描述】:

我正在尝试在 Python 中实现对 Instagram API 的签名调用。目前我的标题看起来像这样:

user_agent = 'Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7'
headers = {
    'User-Agent': user_agent,
    "Content-type": "application/x-www-form-urlencoded"
}

我对@9​​87654321@ 给出的说明尝试了几种排列方式,包括HMAC 方法 和在我的API 设置页面中启用“Enforce Signed Header”

但我不断收到headers not found403 错误。我只是不知道如何正确编码X-Insta-Forwarded-For

能否请您帮助如何在 Python 中通过标头传递签名调用?
非常感谢...

【问题讨论】:

    标签: python instagram instagram-api


    【解决方案1】:

    这应该为你做。您还需要 Crypto python 库。

    import requests
    from Crypto.Hash import HMAC, SHA256
    
    #change these accordingly
    client_secret = "mysecret"
    client_ip = "127.0.0.1"
    
    hmac = HMAC.new(client_secret, digestmod=SHA256)
    hmac.update(client_ip)
    signature = hmac.hexdigest()
    
    header_string = "%s|%s" % (client_ip, signature)
    
    headers = {
        "X-Insta-Forwarded-For" : header_string,
        #and the rest of your headers
    }
    
    #or use requests.post or del since that's the 
    #only time that this header is used...just 
    #conveying the concept
    resp = requests.get(insta_url, headers=headers)
    

    如果您使用您列出的参考中给出的示例对其进行测试,您可以使用此方法验证您是否获得了正确的哈希

    ip = "200.15.1.1"
    secret = "6dc1787668c64c939929c17683d7cb74"
    hmac = HMAC.new(secret, digestmod=SHA256)
    hmac.update(ip)
    signature = hmac.hexdigest() 
    # should be 7e3c45bc34f56fd8e762ee4590a53c8c2bbce27e967a85484712e5faa0191688
    

    根据参考文档 - “要启用此设置,请编辑您的 OAuth 客户端配置并标记强制签名标头复选框。”所以请确保你也这样做了

    【讨论】:

    • 您好,非常感谢您的回复...不幸的是,我收到错误 NameError: name 'insta_url' is not defined。如果我删除这条线,那么限制就会被强制执行(30 个赞/小时,15 个 cmets/小时)......如何解决这个问题?请帮忙...
    • insta_url 仅用于演示。它应该看起来像api.instagram.com/v1/media/<media ID here>/likes。因此,如果媒体 ID 是 123456,那么我将像这样构造 insta_urlinsta_url = "https://api.instagram.com/v1/media/123456/relationship" 请注意,我将使用“relationship”api,它仅支持带有签名标头的 POST,因此您的请求应该完成像这样requests.post(insta_url, headers=headers)
    • 查看您发布的 api 文档的“强制签名标头”部分,了解支持签名标头的可用方法。页面下方还有更多代码演示,您甚至可以通过 curl 进行测试
    • 感谢您的回复...现在运行良好...我使用 urllib 和 urllib2 代替 requests 方法(只是无法弄清楚请求!)...关键部分是启用 Instagram API 页面中的 BOTH 复选框以确保成功通过已签名的标头以利用已签名的呼叫限制(超过未签名的呼叫限制)...干杯:)
    • 太棒了!很高兴听到。你能把我的帖子作为答案吗:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    相关资源
    最近更新 更多