@@ -433,31 +433,33 @@ def run_local_server(
433
433
bind_addr or host , port , wsgi_app , handler_class = _WSGIRequestHandler
434
434
)
435
435
436
- redirect_uri_format = (
437
- "http://{}:{}/" if redirect_uri_trailing_slash else "http://{}:{}"
438
- )
439
- self .redirect_uri = redirect_uri_format .format (host , local_server .server_port )
440
- auth_url , _ = self .authorization_url (** kwargs )
441
-
442
- if open_browser :
443
- # if browser is None it defaults to default browser
444
- webbrowser .get (browser ).open (auth_url , new = 1 , autoraise = True )
445
-
446
- if authorization_prompt_message :
447
- print (authorization_prompt_message .format (url = auth_url ))
448
-
449
- local_server .timeout = timeout_seconds
450
- local_server .handle_request ()
451
-
452
- # Note: using https here because oauthlib is very picky that
453
- # OAuth 2.0 should only occur over https.
454
- authorization_response = wsgi_app .last_request_uri .replace ("http" , "https" )
455
- self .fetch_token (
456
- authorization_response = authorization_response , audience = token_audience
457
- )
458
-
459
- # This closes the socket
460
- local_server .server_close ()
436
+ try :
437
+ redirect_uri_format = (
438
+ "http://{}:{}/" if redirect_uri_trailing_slash else "http://{}:{}"
439
+ )
440
+ self .redirect_uri = redirect_uri_format .format (
441
+ host , local_server .server_port
442
+ )
443
+ auth_url , _ = self .authorization_url (** kwargs )
444
+
445
+ if open_browser :
446
+ # if browser is None it defaults to default browser
447
+ webbrowser .get (browser ).open (auth_url , new = 1 , autoraise = True )
448
+
449
+ if authorization_prompt_message :
450
+ print (authorization_prompt_message .format (url = auth_url ))
451
+
452
+ local_server .timeout = timeout_seconds
453
+ local_server .handle_request ()
454
+
455
+ # Note: using https here because oauthlib is very picky that
456
+ # OAuth 2.0 should only occur over https.
457
+ authorization_response = wsgi_app .last_request_uri .replace ("http" , "https" )
458
+ self .fetch_token (
459
+ authorization_response = authorization_response , audience = token_audience
460
+ )
461
+ finally :
462
+ local_server .server_close ()
461
463
462
464
return self .credentials
463
465
0 commit comments