【发布时间】:2021-12-07 12:27:30
【问题描述】:
我正在使用下面的代码调用 LinkedIn API,它可以满足我的需求。 但是,当我在循环中使用几乎相同的代码时,它会返回类型错误。
它返回一个类型错误:
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 的一个链接,
(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})
更新代码感谢您的 cmets。
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"])
【问题讨论】:
-
请提供错误的完整堆栈跟踪,它通常包含有价值的信息
-
我相信当您使用 headers[access_token] 时错误发生了变化,发生了什么?
-
在第二个 sn-p 中,
shids, requests, auth, headers没有定义。如需调试帮助,您需要提供minimal reproducible example,包括完整但最少的代码、示例输入和预期输出。你可以edit。有关更多提示,请参阅How to Ask。 -
File "C:\Users\pchmurzynski\OneDrive - Centiq Ltd\Documents\Python\mergedreqs.py",第 59 行,在
headers = headers(access_token) # 使标头附加到 API 调用。 TypeError: 'dict' 对象不可调用 -
是的,你用
headers(access_token)可以看到报错,但是你用headers[access_token]或者headers.get(access_token)报错会不一样,但是你没说他们是什么跨度>
标签: python python-requests linkedin-api