@@ -392,28 +392,32 @@ def __init__(
392392 password ,
393393 two_factor_callback = None ,
394394 scopes = None ,
395+ retries = 0 ,
395396 ):
396397 """Represent a single personal-use authorization to Reddit's API.
397398
398399 :param authenticator: An instance of :class:`TrustedAuthenticator`.
399400 :param username: The Reddit username of one of the application's developers.
400401 :param password: The password associated with ``username``.
401- :param two_factor_callback: A function that returns OTPs (One-Time
402- Passcodes), also known as 2FA auth codes. If this function is
403- provided, prawcore will call it when authenticating.
402+ :param two_factor_callback: (Optional) A function that returns a two factor
403+ authentication code.
404404 :param scopes: (Optional) A list of OAuth scopes to request authorization for
405405 (default: None). The scope ``*`` is requested when the default argument is
406406 used.
407+ :param retries: (Optional) The number of times to retry an authorization
408+ attempt that raises an ``OAuthException`` (default: 0). The argument should be a
409+ nonnegative integer less than or equal to ten. This setting is ignored if
410+ two_factor_callback does not return a value that is ``True``.
407411
408412 """
409- super (ScriptAuthorizer , self ).__init__ (authenticator )
413+ super ().__init__ (authenticator )
410414 self ._password = password
415+ self ._retries = abs (retries )
411416 self ._scopes = scopes
412417 self ._two_factor_callback = two_factor_callback
413418 self ._username = username
414419
415- def refresh (self ):
416- """Obtain a new personal-use script type access token."""
420+ def _refresh_with_retries (self , count = 0 ):
417421 additional_kwargs = {}
418422 if self ._scopes :
419423 additional_kwargs ["scope" ] = " " .join (self ._scopes )
@@ -422,9 +426,21 @@ def refresh(self):
422426 )
423427 if two_factor_code :
424428 additional_kwargs ["otp" ] = two_factor_code
425- self ._request_token (
426- grant_type = "password" ,
427- username = self ._username ,
428- password = self ._password ,
429- ** additional_kwargs ,
430- )
429+ try :
430+ self ._request_token (
431+ grant_type = "password" ,
432+ username = self ._username ,
433+ password = self ._password ,
434+ ** additional_kwargs ,
435+ )
436+ except OAuthException :
437+ if two_factor_code :
438+ if count >= min (self ._retries , 10 ):
439+ raise
440+ self ._refresh_with_retries (count + 1 )
441+ else :
442+ raise
443+
444+ def refresh (self ):
445+ """Obtain a new personal-use script type access token."""
446+ self ._refresh_with_retries ()
0 commit comments