Skip to content

Commit bdff06a

Browse files
committed
ref(app.py): use Session as a singleton
1 parent 7647569 commit bdff06a

1 file changed

Lines changed: 22 additions & 14 deletions

File tree

rootfs/api/models/app.py

Lines changed: 22 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,23 @@
2727

2828
logger = logging.getLogger(__name__)
2929

30+
session = None
31+
32+
33+
def get_session():
34+
global session
35+
if session is None:
36+
session = requests.Session()
37+
session.headers = {
38+
# https://toolbelt.readthedocs.org/en/latest/user-agent.html#user-agent-constructor
39+
'User-Agent': user_agent('Deis Controller', deis_version),
40+
}
41+
# `mount` a custom adapter that retries failed connections for HTTP and HTTPS requests.
42+
# http://docs.python-requests.org/en/latest/api/#requests.adapters.HTTPAdapter
43+
session.mount('http://', requests.adapters.HTTPAdapter(max_retries=10))
44+
session.mount('https://', requests.adapters.HTTPAdapter(max_retries=10))
45+
return session
46+
3047

3148
# http://kubernetes.io/v1.1/docs/design/identifiers.html
3249
def validate_id_is_docker_compatible(value):
@@ -525,27 +542,18 @@ def verify_application_health(self, **kwargs):
525542
allowed.remove(404)
526543
req_timeout = 3
527544

528-
session = requests.Session()
529-
session.headers = {
530-
# https://toolbelt.readthedocs.org/en/latest/user-agent.html#user-agent-constructor
531-
'User-Agent': user_agent('Deis Controller', deis_version),
532-
# set the Host header for the application being checked - not used for actual routing
533-
'Host': '{}.{}.nip.io'.format(self.id, settings.ROUTER_HOST)
534-
}
535-
536-
# `mount` a custom adapter that retries failed connections for HTTP and HTTPS requests.
537-
# http://docs.python-requests.org/en/latest/api/#requests.adapters.HTTPAdapter
538-
session.mount('http://', requests.adapters.HTTPAdapter(max_retries=10))
539-
session.mount('https://', requests.adapters.HTTPAdapter(max_retries=10))
540-
541545
# Give the router max of 10 tries or max 30 seconds to become healthy
542546
# Uses time module to account for the timout value of 3 seconds
543547
start = time.time()
544548
failed = False
549+
headers = {
550+
# set the Host header for the application being checked - not used for actual routing
551+
'Host': '{}.{}.nip.io'.format(self.id, settings.ROUTER_HOST),
552+
}
545553
for _ in range(10):
546554
try:
547555
# http://docs.python-requests.org/en/master/user/advanced/#timeouts
548-
response = session.get(url, timeout=req_timeout)
556+
response = get_session().get(url, timeout=req_timeout, headers=headers)
549557
failed = False
550558
except requests.exceptions.RequestException:
551559
# In case of a failure where response object is not available

0 commit comments

Comments
 (0)