How to Handle Exceptions Within the Python Method

Asked 2 years ago, Updated 2 years ago, 118 views

I sent a request to TwitterAPI on python3 and wrote the code to store the returned value.

Authenticate OAuth in the library ②Send a request to twitterAPI

Storing API request limits in requests_limit It says that
I would like to use the exception handling part of OAuth authentication in の as a method, but I can't apply it well.I would like to write a method to retry OAuth authentication and try again if the exception handling does not work.

 from requests_oauthlib import OAuth1 Session
CK="xxxxxx"#Consumer key
CS="xxxxxx"#Consumer secret
AT="xxxxxx"#Access token
AS="xxxxxx"#Access token secret
twitter=OAuth1Session(CK,CS,AT,AS)#Authentication Processing
request_status_url="https://api.twitter.com/1.1/statuses/retweets/:id.json"#Request URL
for i in range(3): #just 3 times
    # ↓↓↓↓↓ Where do you want to use the method ↓↓↓↓↓
    try:
        api_response=twitter.get(request_status_url)
    except:
        twitter = OAuth1 Session (CK, CS, AT, AS)
        continue
    # ↑↑↑↑↑ Where do you want to use the method ↑↑↑↑↑
    requests_limit = api_response.headers ['x-rate-limit-remaining'] # Get Remaining Requestable Remaining
    print(str(i)+":"+str(requests_limit))

The above works fine, but if you use the authentication partial method as shown below, the try statement does not work properly.I would appreciate it if you could give me some advice on how to write it down.

 from requests_oauthlib import OAuth1 Session
def request_authorization (request_status_url, CK, CS, AT, AS):
    try:
        api_response=twitter.get(request_status_url)
    except:
        twitter = OAuth1 Session (CK, CS, AT, AS)
        api_response=request_authorization(request_status_url)
    return api_response
CK="xxxxxx"#Consumer key
CS="xxxxxx"#Consumer secret
AT="xxxxxx"#Access token
AS="xxxxxx"#Access token secret
twitter=OAuth1Session(CK,CS,AT,AS)#Authentication Processing
request_status_url= 
"https://api.twitter.com/1.1/statuses/retweets/:id.json" #Request URL
for i in range(3): #just 3 times
    api_response=request_authorization(request_status_url, CK, CS, AT, AS)
    requests_limit = api_response.headers ['x-rate-limit-remaining'] # Get Remaining Requestable Remaining
    print(str(i)+":"+str(requests_limit))

Error code when executing the above code.

UnboundLocalError Traceback (most recent call last)
<ipython-input-7-25ff3a35d752>in request_authorization (request_status_url, CK, CS, AT, AS)
      3try:
---->4 api_response=twitter.get(request_status_url)
      5 except:

UnboundLocalError: local variable 'twitter' referred before assignment

During handling of the above exception, another exception occurred:

TypeError Traceback (most recent call last)
<ipython-input-7-25ff3a35d752>in<module>()
     15 for i in range (3): # 3 random times
     16# ↓↓↓↓↓ Where do you want to use the method ↓↓↓↓↓
--- >17 api_response=request_authorization(request_status_url, CK, CS, AT, AS)
     18# ↑↑↑↑↑ Where do you want to use the method ↑↑↑↑↑
     19 requests_limit = api_response.headers ['x-rate-limit-remaining'] # Get Remaining Requestable Remaining

<ipython-input-7-25ff3a35d752>in request_authorization (request_status_url, CK, CS, AT, AS)
      5 except:
      6 twitter = OAuth1 Session (CK, CS, AT, AS)
---->7api_response=request_authorization(request_status_url)
      8 return api_response
      9CK="yGWfCjVCS4uFHRA4q08RIWM2u"#Consumer key

TypeError: request_authorization() missing 4 required positional arguments: 'CK', 'CS', 'AT', and 'AS'

By the way, the reason why OAuth authentication is not only one time is because sometimes OAuth authentication expires when a large number of values are retrieved from the API and the execution takes several hours.The following error codes are used when authentication has expired:

Traceback (most recent call last):
〜〜
〜〜
ConnectionResetError: [Errno54] Connection reset by peer
During handling of the above exception, another exception occurred:

python python3 twitter oauth

2022-09-30 17:40

1 Answers

Answer only why the error occurs.

TypeError: request_authorization() missing 4 required positional arguments: 'CK', 'CS', 'AT', and 'AS'

This means that the request_authorization function does not have enough arguments CK, CS, AT, AS.

def request_authorization (request_status_url, CK, CS, AT, AS):
    try:
        api_response=twitter.get(request_status_url)
    except:
        twitter=OAuth1Session(CK,CS,AT,AS)#<=Just substitute the local variable twitter
        api_response=request_authorization(request_status_url)#<= argument missing
    return api_response

This will avoid errors, but this code will never re-create the Twitter OAuthSession when the rate-limit is reached.

Therefore, I think it would be better to do the following.

  • Creating an OAuthSession for Twitter is also done in request_authorization
  • Except: Recursively calls request_authorization only for exceptions with rate_limit instead of


2022-09-30 17:40

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.