在循环中使用字典中的变量附加到 API 调用

Using a variable from a dictionary in a loop to attach to an API call

我正在使用下面的代码调用 LinkedIn API,它可以满足我的要求。 但是,当我在循环中使用几乎相同的代码时,它 returns 类型错误。

它 returns 类型错误:

File "C:\Users\pchmurzynski\OneDrive - Centiq Ltd\Documents\Python\mergedreqs.py", line 54, in <module>
    auth_headers = headers(access_token)
TypeError: 'dict' object is not callable

这行有问题(同样,在循环外工作正常):

headers = headers(access_token)

我尝试将其更改为

headers = headers.get(access_token)

headers = headers[access_token]

编辑: 我也试过这个,有同样的错误:

auth_headers = headers(access_token)

但这并没有帮助。我究竟做错了什么?为什么字典在循环外工作正常,但在循环内却不行,我应该怎么做才能让它工作?

我希望实现的是获得一个列表,我可以将其另存为 json,其中包含为“shids”列表中的每个 ID 调用的共享统计信息。这可以通过单独的请求来完成——一个 ID 一个 link,

(f'https://api.linkedin.com/v2/organizationalEntityShareStatistics?q=organizationalEntity&organizationalEntity=urn%3Ali%3Aorganization%3A77487&ugcPosts=List(urn%3Ali%3AugcPost%3A{shid})

或带有 ID 列表的请求。

(f'https://api.linkedin.com/v2/organizationalEntityShareStatistics?q=organizationalEntity&organizationalEntity=urn%3Ali%3Aorganization%3A77487&ugcPosts=List(urn%3Ali%3AugcPost%3A{shid},urn%3Ali%3AugcPost%3A{shid2},...,urn%3Ali%3AugcPost%3A{shidx})

更新代码 感谢您的评论。

shlink = ("https://api.linkedin.com/v2/organizationalEntityShareStatistics?q=organizationalEntity&organizationalEntity=urn%3Ali%3Aorganization%3A77487&shares=List(urn%3Ali%3Ashare%3A{})")
#loop through the list of share ids and make an api request for each of them
shares = []
token = auth(credentials) # Authenticate the API
headers = fheaders(token) # Make the headers to attach to the API call.
for shid in shids:
    #create a request link for each sh id
    r = (shlink.format(shid))
    #call the api
    res = requests.get(r, headers = auth_headers)
    share_stats = res.json()
    #append the shares list with the responce
    shares.append(share_stats["elements"])

works fine outside the loop

因为在循环中,你重新定义了变量。添加打印语句以显示它

from liapiauth import auth, headers  # one type

for ...:
    ... 
    print(type(headers))
    headers = headers(access_token)  # now set to another type
    print(type(headers))

经验教训 - 不要覆盖您的导入


一些重构 - 你的授权令牌没有改变,所以不要把它放在循环中;您可以对所有 LinkedIn API 查询使用一种方法

from liapiauth import auth, headers
import requests

API_PREFIX = 'https://api.linkedin.com/v2'

SHARES_ENDPOINT_FMT = '/organizationalEntityShareStatistics?q=organizationalEntity&organizationalEntity=urn%3Ali%3Aorganization%3A77487&shares=List(urn%3Ali%3Ashare%3A{}'

def get_linkedin_response(endpoint, headers):
    return requests.get(API_PREFIX + endpoint, headers=headers)

def main(access_token=None):
    if access_token is None:
       raise ValueError('Access-Token not defined')
    auth_headers = headers(access_token)

    shares = []
    for shid in shids:
        endpoint = SHARES_ENDPOINT_FMT.format(shid)
        resp = get_linkedin_response(endpoint, auth_headers)
        if resp.status_code // 100 == 2: 
            share_stats = resp.json()
            shares.append(share_stats[1])

    # TODO: extract your data here
    idlist = [el["id"] for el in shares_list["elements"]]

if __name__ == '__main__':
    credentials = 'credentials.json'
    main(auth(credentials))