![](/img/trans.png)
[英]400 Error in REACT JS while calling Post API developed in Python Flask using fetch method
[英]How to avoid or skip error 400 in python while calling the API
注意:-我在引用堆栈溢出中的几个示例后编写了代码,但仍然无法获得所需的输出
我有一个Python脚本,其中循环使用Instagram API进行迭代。 我提供了user_id作为API的输入,该API获得了帖子的数量,关注者的数量和关注者的数量。 每次收到响应时,我都将其加载到JSON模式中,并追加到列表data1,data2和data3。
问题是:=有些帐户是私人帐户,不允许对其进行API调用。 当我在IDLE Python Shell中运行脚本时,它给出了错误
Traceback (most recent call last):
File "<pyshell#144>", line 18, in <module>
beta=json.load(url)
File "C:\Users\rnair\AppData\Local\Programs\Python\Python35\lib\site- packages\simplejson-3.8.2-py3.5-win-amd64.egg\simplejson\__init__.py", line 455, in load
return loads(fp.read(),
File "C:\Users\rnair\AppData\Local\Programs\Python\Python35\lib\tempfile.py", line 483, in func_wrapper
return func(*args, **kwargs)
**ValueError: read of closed file**
但是JSON包含以下内容:
{
"meta": {
"error_type": "APINotAllowedError",
"code": 400,
"error_message": "you cannot view this resource"
}
}
我的代码是:-
for r in range(307,601):
var=r,sheet.cell(row=r,column=2).value
xy=var[1]
ij=str(xy)
if xy=="Account Deleted":
data1.append('null')
data2.append('null')
data3.append('null')
continue
myopener=Myopen()
try:
url=myopener.open('https://api.instagram.com/v1/users/'+ij+'/?access_token=641567093.1fb234f.a0ffbe574e844e1c818145097050cf33')
except urllib.error.HTTPError as e: // I want the change here
data1.append('Private Account')
data2.append('Private Account')
data3.append('Private Account')
continue
beta=json.load(url)
item=beta['data']['counts']
data1.append(item['media'])
data2.append(item['followed_by'])
data3.append(item['follows'])
我正在使用Python版本3.5.2。 主要问题是, 如果循环运行并且特定的调用被阻止并收到此错误,如何避免它并继续运行下一个迭代? 另外,如果该帐户是私人帐户,我想将“私人帐户”附加到列表中。
看起来实际上是在获取URL的代码在您的自定义类型-“ Myopen”(未显示)中。 它也像仍在执行其不扔你期待的HTTPError,因为你的“json.load”行(并导致正被抛出ValueError异常)。
如果要触发错误处理块,则需要检查响应状态代码以查看Myopen中的!= 200,并抛出您期望的HTTPError而不是现在执行的任何操作。
我个人不熟悉FancyURLOpener
,但看起来它支持getcode
方法。 也许尝试这样的事情,而不是期望HTTPError:
url = myopener.open('yoururl')
if url.getcode() == 400:
data1.append('Private Account')
data2.append('Private Account')
data3.append('Private Account')
continue
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.