如果出现连接错误,如何以编程方式更改参数?

时间:2019-02-17 02:15:20

标签: python connection

我正在调用API。发出请求时,我达到了最大尝试次数,但出现连接错误。我想通过增加url中的数字来以编程方式编辑url。我确实知道如何以编程方式更改参数,但不确定在遇到连接错误时如何更改/增加参数。

我的使用语言是Python,并且我正在使用请求库。

代码段     Libraries importing from requests.auth import HTTPBasicAuth import requests from requests.exceptions import ConnectionError

```def make_request(data , id=None):
     url = "http://server001.net:8080/?id="
     result = {}
     if id:
       response = requests.get(url +id , auth=HTTPBasicAuth('uname', 'pass'))
       return response
     else :
       for line in data:
         try:
           response = requests.get(url +line , auth=HTTPBasicAuth('uname', 'pass'))
            result = html_parser2(response)
            if result:
                write_csv(result)
            else:
                pass
         except ConnectionError as e:
           print (e)```

预期输出     url = "http://server001.net:8080/?id=" url_edited = "http://server002.net:8080/?id=" 仅当我达到最大尝试次数时,即得到例外或 否则继续请求相同的网址。

1 个答案:

答案 0 :(得分:0)

选项之一是用try..except循环将while块括起来。 此外,也许您也应该将您的第一个requests.get放入try..except块中。 还应尝试避免在一个try..except块中进行多个无关的操作,即仅在成功连接后执行write_csv

def make_request(data , id=None):
    url = 'http://server001.net:8080/?id={}'
    connection_failed = False
    response = None
    if id:
        try:
            response = requests.get(url.format(id) , auth=HTTPBasicAuth('uname', 'pass'))
        except ConnectionError as e:
            print('id = {}, e: {}'.format(id, e))
    else:
        for line in data:
            while not connection_failed:
                try:
                    response = requests.get(url.format(line) , auth=HTTPBasicAuth('uname', 'pass'))
                except ConnectionError as e:
                    connection_failed = True
                    print('line = {}, e: {}'.format(id, e))
                else:
                    result = html_parser2(response)
                    if result:
                        write_csv(result)
    return response
def make_request(data , id=None):
    url = 'http://server001.net:8080/?id={}'
    response = None
    if id:
        try:
            response = requests.get(url.format(id) , auth=HTTPBasicAuth('uname', 'pass'))
        except ConnectionError as e:
            print('id = {}, e: {}'.format(id, e))
    else:
        for line in data:
            try:
                response = requests.get(url.format(line) , auth=HTTPBasicAuth('uname', 'pass'))
            except ConnectionError as e:
                print('line = {}, e: {}'.format(id, e))
            else:
                result = html_parser2(response)
                if result:
                    write_csv(result)
                break
    return response