【问题标题】:Re-run the execution if api call fails - [ Python2.7]如果 api 调用失败,重新运行执行 - [ Python2.7]
【发布时间】:2017-04-11 23:01:59
【问题描述】:

我正在运行一个从 API url 获取 json 数据的代码,场景是我正在尝试自定义异常,而未获取 URL 响应(有时响应显示 200 仍然它不获取数据)在此如果代码应该从头开始重新执行。

代码:

import json
import urllib
url = 'www.google.com'
status = url.getcode()
if(status != 200):
   # re-execute the code
data = json.load(urllib.urlopen(url))
if (data == null):
   #re-execute the code

通过互联网搜索时找不到合适的解决方案

有人可以帮忙吗?

【问题讨论】:

  • 使用循环怎么样?另外null在Python中不存在,你可以使用data is None或者if not data来验证。
  • 什么是null

标签: python python-2.7 api networking


【解决方案1】:

按照您目前的逻辑,我认为这可以帮助您:

import json
import urllib

url = 'www.google.com'

while True:
    status = url.getcode()
    if status != 200:
        continue
    data = json.load(urllib.urlopen(url))
    if not data:
        continue
    break

您还可以通过以下方式对其进行一些改进:

import json
import urllib

url = 'www.google.com'
status = url.getcode()
data = json.load(urllib.urlopen(url))

while status != 200 or not data:
    status = url.getcode()
    data = json.load(urllib.urlopen(url))

【讨论】:

    【解决方案2】:
    import json
    import urllib
    
    URL = 'www.google.com'
    
    def get_data_status(url):
        return (json.load(urllib.urlopen(url)), url.getcode())
    
    while 1:
        data, status = get_data_status(URL)
        if data  and (status==200): 
            break
    

    None、False、空字符串、空字典、空数组和 0 是假值。我认为您没有正确使用 null 。当 Python 解码 JSON 时,它会将 null 转换为它的 null 对象,即 None。

    ETA:关于 cmets:

    如果 api 没有任何数据,它会将响应返回为 null,因此给定 null

    在 'if(data == null)' 之后我还有几行要执行

    好吧,如果你真的从 json 请求中得到 str(null) 并且你想在那个事件上“执行几行代码”:

    while 1:
        data, status = get_data_status(URL)
        if (data!='null')  and (status==200): 
            break
        elif (data='null'):
            print 'execute a few more lines of "null" data code'
        elif (status!=200):
            print 'execute a few more lines of wrong status code'
    
    print 'exiting while loop with good data and status 200'
    

    【讨论】:

    • 这会产生两个错误错误:1. statusdata 未定义。 2.null在Python中不存在
    • 是的,我抓住了前两个,正在按照您的评论进行编辑。不确定操作的 null 响应是什么意思?
    • 我同意你的看法。可能null 是一个变量,但由于我看到通常在文件开头的导入,我假设问的人有 Java 经验。
    • 感谢回复
    • 这会从顶部重新执行代码吗?在 'if(data == null)' 之后我还有几行要执行
    猜你喜欢
    • 2023-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-03
    • 1970-01-01
    • 2020-06-03
    相关资源
    最近更新 更多