What about reducing the granularity of try-catch? Or paste your code for analysis. What you said about continuing to execute the original code after an exception is a bit vague.
【Edit】 After reading the other two answers, they are basically the two ideas I put forward in the comments below. It should be said that everyone’s ideas are basically the same. Modify it here and give me a code plan:
# introduce a new function # @return: succeed, new_ip def exec(ip, url): try: # do what you want to do return True, ip except: # change your id return False, new_ip # your original logics urls = [url1, url2, ..., url10] i = 0 ip = ip1 while i <= len(urls): succeed, ip = exec(ip, urls[i]) if succeed: i +=1
I just wrote one, which is to generateAccess Token的,Access Token在数据库中是唯一的,但是生成Access Token的函数不能保证每次生成的Access Token都是不一样的。所以我用了一个很恶心的whileloop. It’s roughly as follows:
while True: try: access_token = make_token() access_token.add_to_db break except IntegrityError as e: if e.orig.args[0] == 1062: # 这种情况下,发生了mysql 1062异常,说明数据库中有重复的access token,需要反复生成新的,直至不同 pass else: raise e
Not clever, but it works.
Or talk about your business, maybe it doesn’t have to be so disgusting.
Original text of the question: This is a bit more troublesome for me. For example, I need to request 10 URLs in sequence. If the fifth URL is disconnected, an error will be reported, and then I will execute the code below except to change the IP. It is impossible every time Please write a while request, this is simply unreadable
My plan:
def r(uri, data): while True: try: res = requests(uri, data) return res except: change_ip()
This solution should be possible for single-process and single-thread synchronous requests.
What about reducing the granularity of try-catch? Or paste your code for analysis. What you said about continuing to execute the original code after an exception is a bit vague.
【Edit】
After reading the other two answers, they are basically the two ideas I put forward in the comments below. It should be said that everyone’s ideas are basically the same. Modify it here and give me a code plan:
I just wrote one, which is to generate
Access Token
的,Access Token
在数据库中是唯一的,但是生成Access Token
的函数不能保证每次生成的Access Token
都是不一样的。所以我用了一个很恶心的while
loop. It’s roughly as follows:Not clever, but it works.
Or talk about your business, maybe it doesn’t have to be so disgusting.
My plan:
This solution should be possible for single-process and single-thread synchronous requests.