22from __future__ import annotations
33
44try :
5- import flask
5+ from flask import (
6+ has_request_context as _has_request_context ,
7+ request
8+ )
69except ImportError :
7- from mp_api .client .core .exceptions import MPRestError
8-
9- raise MPRestError ("`flask` must be installed to use server utilities." )
10-
11- import requests
10+ _has_request_context = None
11+ request = None
1212
1313from mp_api .client import MPRester
1414from mp_api .client .core .utils import validate_api_key
1515
16- SESSION = requests .Session ()
16+ def has_request_context () -> bool :
17+ """Determine if the current context is a request.
1718
19+ Returns
20+ --------
21+ bool : True if in a request context
22+ False if flask is not installed or not in a request context.
23+ """
24+ return _has_request_context is not None and _has_request_context ()
25+
26+ def get_request_headers () -> dict [str ,Any ]:
27+ """Get the headers if operating in a request context.
28+
29+ Returns
30+ --------
31+ dict of str to Any
32+ Empty dict if flask is not installed, or not in a request context.
33+ Request headers otherwise.
34+ """
35+ return request .headers if has_request_context () else {}
1836
1937def is_localhost () -> bool :
2038 """Determine if current env is local or production.
@@ -24,8 +42,8 @@ def is_localhost() -> bool:
2442 """
2543 return (
2644 True
27- if not flask . has_request_context ()
28- else flask . request . headers .get ("Host" , "" ).startswith (
45+ if not has_request_context ()
46+ else get_request_headers () .get ("Host" , "" ).startswith (
2947 ("localhost:" , "127.0.0.1:" , "0.0.0.0:" )
3048 )
3149 )
@@ -37,7 +55,7 @@ def get_consumer() -> dict[str, str]:
3755 Returns:
3856 dict of str to str, the headers associated with the consumer
3957 """
40- if not flask . has_request_context ():
58+ if not has_request_context ():
4159 return {}
4260
4361 names = [
@@ -48,7 +66,7 @@ def get_consumer() -> dict[str, str]:
4866 "X-Authenticated-Groups" , # groups this user belongs to
4967 "X-Consumer-Groups" , # same as X-Authenticated-Groups
5068 ]
51- headers = flask . request . headers
69+ headers = get_request_headers ()
5270 return {name : headers [name ] for name in names if headers .get (name ) is not None }
5371
5472
0 commit comments