Skip to content

Commit 7e4134b

Browse files
committed
tmp 5
Signed-off-by: kvmw <[email protected]>
1 parent 5a3baa3 commit 7e4134b

File tree

6 files changed

+105
-73
lines changed

6 files changed

+105
-73
lines changed

greeter-messages/app.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
"""Flask application for the greeter-messages service."""
2+
13
import os
24
import logging
35
from flask import Flask, request
@@ -11,15 +13,16 @@
1113
try:
1214
init_client()
1315
logger.info("Eureka client initialized successfully")
14-
except Exception as e:
15-
logger.error(f"Failed to initialize Eureka client: {e}")
16+
except (ValueError, ImportError, OSError) as e:
17+
logger.error("Failed to initialize Eureka client: %s", e)
1618

1719
@app.route('/greeting')
1820
def greeting():
21+
"""Handle greeting requests."""
1922
salutation = request.args.get('salutation', 'Hello')
2023
name = request.args.get('name', 'Bob')
21-
22-
logger.info(f"Greeting request: salutation='{salutation}', name='{name}'")
24+
25+
logger.info("Greeting request: salutation='%s', name='%s'", salutation, name)
2326
return f"{salutation}, {name}!"
2427

2528
if __name__ == '__main__':

greeter-messages/eureka.py

Lines changed: 31 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
1+
"""Eureka client integration for service discovery and registration."""
2+
13
import os
24
import urllib.request
35
import logging
6+
from typing import Union
7+
from urllib.error import URLError
8+
49
from cfenv import AppEnv
510
from oauth2 import OAuth2Client
6-
import py_eureka_client.eureka_client as eureka_client
7-
import py_eureka_client.http_client as http_client
8-
from urllib.error import URLError
9-
from typing import Union
11+
from py_eureka_client import eureka_client, http_client
1012

1113
logger = logging.getLogger(__name__)
1214

@@ -16,6 +18,7 @@ class _OAuth2HttpClient(http_client.HttpClient):
1618
"""
1719

1820
def __init__(self, credentials: dict):
21+
"""Initialize the OAuth2 HTTP client with credentials."""
1922
self.oauth_client = OAuth2Client(
2023
client_id=credentials['client_id'],
2124
client_secret=credentials['client_secret'],
@@ -24,29 +27,32 @@ def __init__(self, credentials: dict):
2427

2528
async def urlopen(self, request: Union[str, http_client.HttpRequest] = None,
2629
data: bytes = None, timeout: float = None) -> http_client.HttpResponse:
30+
"""Open a URL with OAuth2 authentication."""
2731
if isinstance(request, http_client.HttpRequest):
2832
req = request
2933
elif isinstance(request, str):
3034
req = http_client.HttpRequest(request, headers={'Accept-Encoding': 'gzip'})
3135
else:
3236
raise URLError("Invalid URL")
3337

34-
req = req._to_urllib_request()
38+
req = req._to_urllib_request() # pylint: disable=protected-access
3539
req.add_header("Connection", "close")
3640
req.add_header("Authorization", f"Bearer {self.oauth_client.get_access_token()}")
37-
res = urllib.request.urlopen(req, data=data, timeout=timeout)
38-
return http_client.HttpResponse(res)
41+
with urllib.request.urlopen(req, data=data, timeout=timeout) as res:
42+
return http_client.HttpResponse(res)
43+
44+
def get_oauth_client(self):
45+
"""Get the OAuth2 client instance."""
46+
return self.oauth_client
3947

4048
def _on_err(err_type: str, err: Exception):
41-
logger.error(f"Eureka client error - Type: {err_type}, Error: {err}")
49+
"""Handle Eureka client errors."""
50+
logger.error("Eureka client error - Type: %s, Error: %s", err_type, err)
4251
if err_type in (eureka_client.ERROR_REGISTER, eureka_client.ERROR_DISCOVER):
4352
eureka_client.stop()
4453

4554
def init_client():
46-
"""
47-
Initializes the eureka client.
48-
"""
49-
55+
"""Initialize the eureka client."""
5056
env = AppEnv()
5157

5258
service_registry = env.get_service(label="p.service-registry")
@@ -58,16 +64,16 @@ def init_client():
5864
http_client.set_http_client(_OAuth2HttpClient(credentials))
5965

6066
eureka_client.init(
61-
app_name=env.name,
62-
instance_host=env.uris[0],
63-
instance_ip=os.getenv('CF_INSTANCE_INTERNAL_IP'),
64-
instance_id=f"{env.uris[0]}:{env.app.get('instance_id') or '0'}",
65-
instance_unsecure_port_enabled=True,
66-
instance_port=80,
67-
instance_secure_port_enabled=True,
68-
instance_secure_port=443,
69-
vip_adr='UNKNOWN',
70-
secure_vip_addr='UNKNOWN',
71-
eureka_server=credentials['uri'],
72-
on_error=_on_err
73-
)
67+
app_name=env.name,
68+
instance_host=env.uris[0],
69+
instance_ip=os.getenv('CF_INSTANCE_INTERNAL_IP'),
70+
instance_id=f"{env.uris[0]}:{env.app.get('instance_id') or '0'}",
71+
instance_unsecure_port_enabled=True,
72+
instance_port=80,
73+
instance_secure_port_enabled=True,
74+
instance_secure_port=443,
75+
vip_adr='UNKNOWN',
76+
secure_vip_addr='UNKNOWN',
77+
eureka_server=credentials['uri'],
78+
on_error=_on_err
79+
)

greeter-messages/oauth2.py

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
"""OAuth2 client for handling client credentials flow with token caching."""
2+
13
import time
24
import logging
35
from typing import Optional
@@ -6,25 +8,26 @@
68
logger = logging.getLogger(__name__)
79

810
class OAuth2Client:
9-
"""OAuth 2.0 client for handling client credentials flow with token caching"""
11+
"""OAuth 2.0 client for handling client credentials flow with token caching."""
1012

1113
def __init__(self, client_id: str, client_secret: str, access_token_uri: str):
14+
"""Initialize the OAuth2 client."""
1215
self.client_id = client_id
1316
self.client_secret = client_secret
1417
self.access_token_uri = access_token_uri
1518
self.access_token: Optional[str] = None
1619
self.token_expires_at: Optional[float] = None
1720

1821
def _is_token_expired(self, buffer_seconds: int = 30) -> bool:
19-
"""Check if the current token is expired or will expire soon"""
22+
"""Check if the current token is expired or will expire soon."""
2023
if not self.access_token or not self.token_expires_at:
2124
return True
2225

2326
# Add buffer time to refresh token before it actually expires
2427
return time.time() >= (self.token_expires_at - buffer_seconds)
2528

2629
def _request_new_token(self) -> str:
27-
"""Request a new access token from the OAuth server"""
30+
"""Request a new access token from the OAuth server."""
2831
# Prepare token request
2932
token_data = {
3033
'grant_type': 'client_credentials',
@@ -58,13 +61,18 @@ def _request_new_token(self) -> str:
5861

5962
return self.access_token
6063
except requests.exceptions.RequestException as e:
61-
logger.error(f"Failed to get access token: {e}")
64+
logger.error("Failed to get access token: %s", e)
6265
raise ValueError(f"Failed to get access token: {e}") from e
6366

6467
def get_access_token(self) -> str:
65-
"""Get OAuth 2.0 access token using client credentials flow"""
68+
"""Get OAuth 2.0 access token using client credentials flow."""
6669
# Check if we have a valid cached token
6770
if not self._is_token_expired():
6871
return self.access_token
6972
# Token is expired or doesn't exist, get a new one
7073
return self._request_new_token()
74+
75+
def clear_cache(self) -> None:
76+
"""Clear the cached token."""
77+
self.access_token = None
78+
self.token_expires_at = None

greeter/app.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
"""Flask application for the greeter service."""
2+
13
import os
24
import logging
35
from flask import Flask, request
@@ -11,16 +13,17 @@
1113
try:
1214
init_client()
1315
logger.info("Eureka client initialized successfully")
14-
except Exception as e:
15-
logger.error(f"Failed to initialize Eureka client: {e}")
16+
except (ValueError, ImportError, OSError) as e:
17+
logger.error("Failed to initialize Eureka client: %s", e)
1618

1719
@app.route('/hello')
1820
def hello():
21+
"""Handle hello requests by calling the greeter-messages service."""
1922
salutation = request.args.get('salutation', 'Hello')
2023
name = request.args.get('name', 'Bob')
21-
24+
2225
return call_service("GREETER-MESSAGES", f"/greeting?salutation={salutation}&name={name}")
2326

2427
if __name__ == '__main__':
2528
port = int(os.getenv('PORT', '8080'))
26-
app.run(host='0.0.0.0', port=port)
29+
app.run(host='0.0.0.0', port=port)

greeter/eureka.py

Lines changed: 34 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
1+
"""Eureka client integration for service discovery and registration."""
2+
13
import os
24
import urllib.request
35
import logging
6+
from typing import Union
7+
from urllib.error import URLError
8+
49
from cfenv import AppEnv
510
from oauth2 import OAuth2Client
6-
import py_eureka_client.eureka_client as eureka_client
7-
import py_eureka_client.http_client as http_client
8-
from urllib.error import URLError
9-
from typing import Union
11+
from py_eureka_client import eureka_client, http_client
1012

1113
logger = logging.getLogger(__name__)
1214

@@ -16,6 +18,7 @@ class _OAuth2HttpClient(http_client.HttpClient):
1618
"""
1719

1820
def __init__(self, credentials: dict):
21+
"""Initialize the OAuth2 HTTP client with credentials."""
1922
self.oauth_client = OAuth2Client(
2023
client_id=credentials['client_id'],
2124
client_secret=credentials['client_secret'],
@@ -24,29 +27,32 @@ def __init__(self, credentials: dict):
2427

2528
async def urlopen(self, request: Union[str, http_client.HttpRequest] = None,
2629
data: bytes = None, timeout: float = None) -> http_client.HttpResponse:
30+
"""Open a URL with OAuth2 authentication."""
2731
if isinstance(request, http_client.HttpRequest):
2832
req = request
2933
elif isinstance(request, str):
3034
req = http_client.HttpRequest(request, headers={'Accept-Encoding': 'gzip'})
3135
else:
3236
raise URLError("Invalid URL")
3337

34-
req = req._to_urllib_request()
38+
req = req._to_urllib_request() # pylint: disable=protected-access
3539
req.add_header("Connection", "close")
3640
req.add_header("Authorization", f"Bearer {self.oauth_client.get_access_token()}")
37-
res = urllib.request.urlopen(req, data=data, timeout=timeout)
38-
return http_client.HttpResponse(res)
41+
with urllib.request.urlopen(req, data=data, timeout=timeout) as res:
42+
return http_client.HttpResponse(res)
43+
44+
def get_oauth_client(self):
45+
"""Get the OAuth2 client instance."""
46+
return self.oauth_client
3947

4048
def _on_err(err_type: str, err: Exception):
41-
logger.error(f"Eureka client error - Type: {err_type}, Error: {err}")
49+
"""Handle Eureka client errors."""
50+
logger.error("Eureka client error - Type: %s, Error: %s", err_type, err)
4251
if err_type in (eureka_client.ERROR_REGISTER, eureka_client.ERROR_DISCOVER):
4352
eureka_client.stop()
4453

4554
def init_client():
46-
"""
47-
Initializes the eureka client.
48-
"""
49-
55+
"""Initialize the eureka client."""
5056
env = AppEnv()
5157

5258
service_registry = env.get_service(label="p.service-registry")
@@ -58,26 +64,24 @@ def init_client():
5864
http_client.set_http_client(_OAuth2HttpClient(credentials))
5965

6066
eureka_client.init(
61-
app_name=env.name,
62-
instance_host=env.uris[0],
63-
instance_ip=os.getenv('CF_INSTANCE_INTERNAL_IP'),
64-
instance_id=f"{env.uris[0]}:{env.app.get('instance_id') or '0'}",
65-
instance_unsecure_port_enabled=True,
66-
instance_port=80,
67-
instance_secure_port_enabled=True,
68-
instance_secure_port=443,
69-
vip_adr='UNKNOWN',
70-
secure_vip_addr='UNKNOWN',
71-
eureka_server=credentials['uri'],
72-
on_error=_on_err
73-
)
67+
app_name=env.name,
68+
instance_host=env.uris[0],
69+
instance_ip=os.getenv('CF_INSTANCE_INTERNAL_IP'),
70+
instance_id=f"{env.uris[0]}:{env.app.get('instance_id') or '0'}",
71+
instance_unsecure_port_enabled=True,
72+
instance_port=80,
73+
instance_secure_port_enabled=True,
74+
instance_secure_port=443,
75+
vip_adr='UNKNOWN',
76+
secure_vip_addr='UNKNOWN',
77+
eureka_server=credentials['uri'],
78+
on_error=_on_err
79+
)
7480

7581
def call_service(name: str, path: str):
76-
"""
77-
Calls a service with the given name and path.
78-
"""
82+
"""Call a service with the given name and path."""
7983
try:
8084
return eureka_client.do_service(app_name=name, service=path, prefer_https=True)
8185
except urllib.request.HTTPError as e:
82-
logger.error(f"Error calling service {name} at {path}: {e}")
83-
raise e
86+
logger.error("Error calling service %s at %s: %s", name, path, e)
87+
raise e

greeter/oauth2.py

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
"""OAuth2 client for handling client credentials flow with token caching."""
2+
13
import time
24
import logging
35
from typing import Optional
@@ -6,25 +8,26 @@
68
logger = logging.getLogger(__name__)
79

810
class OAuth2Client:
9-
"""OAuth 2.0 client for handling client credentials flow with token caching"""
11+
"""OAuth 2.0 client for handling client credentials flow with token caching."""
1012

1113
def __init__(self, client_id: str, client_secret: str, access_token_uri: str):
14+
"""Initialize the OAuth2 client."""
1215
self.client_id = client_id
1316
self.client_secret = client_secret
1417
self.access_token_uri = access_token_uri
1518
self.access_token: Optional[str] = None
1619
self.token_expires_at: Optional[float] = None
1720

1821
def _is_token_expired(self, buffer_seconds: int = 30) -> bool:
19-
"""Check if the current token is expired or will expire soon"""
22+
"""Check if the current token is expired or will expire soon."""
2023
if not self.access_token or not self.token_expires_at:
2124
return True
2225

2326
# Add buffer time to refresh token before it actually expires
2427
return time.time() >= (self.token_expires_at - buffer_seconds)
2528

2629
def _request_new_token(self) -> str:
27-
"""Request a new access token from the OAuth server"""
30+
"""Request a new access token from the OAuth server."""
2831
# Prepare token request
2932
token_data = {
3033
'grant_type': 'client_credentials',
@@ -58,13 +61,18 @@ def _request_new_token(self) -> str:
5861

5962
return self.access_token
6063
except requests.exceptions.RequestException as e:
61-
logger.error(f"Failed to get access token: {e}")
64+
logger.error("Failed to get access token: %s", e)
6265
raise ValueError(f"Failed to get access token: {e}") from e
6366

6467
def get_access_token(self) -> str:
65-
"""Get OAuth 2.0 access token using client credentials flow"""
68+
"""Get OAuth 2.0 access token using client credentials flow."""
6669
# Check if we have a valid cached token
6770
if not self._is_token_expired():
6871
return self.access_token
6972
# Token is expired or doesn't exist, get a new one
7073
return self._request_new_token()
74+
75+
def clear_cache(self) -> None:
76+
"""Clear the cached token."""
77+
self.access_token = None
78+
self.token_expires_at = None

0 commit comments

Comments
 (0)