Suppose I have a module data_provider.py
that keeps some code responsible for connecting to external API. In order to establish a connection, an API token needs to be retrieved from the database.
API_TOKEN = get_token_from_database()
class DataProvider:
def __init__(self):
self.api_token = API_TOKEN
def make_query(self):
'''make some request using self.api_token'''
Assuming the code needs to stay in such shape more or less ( API_TOKEN
being a global variable), what would be a good pattern for retrieving the API_TOKEN
from the database?
Obiously now it is not ideal because the module cannot be imported without the database being turned on. Also, I would like to retrieve it only once, not per DataProvider
creation.
Should I for example make API_TOKEN
load lazily or turn it into a function?
I'd probably go with a simple singleton pattern
class DataProvider:
def __init__(self):
self.__api_token = None
def get_token(self):
if self.__api_token is None:
self.__api_token = .....
return self.__api_token
You might want to make get_token(self)
into a property token
instead. That's a matter of taste.
If you have one single DataProvider
object in your application, you could simply remove the global variable and load the token in the __init__
method:
class DataProvider:
def __init__(self):
self.api_token = get_token_from_database()
Another possible lazy loading would be to initialize the global token to None
and then set it at first instanciation of a DataProvider object
API_TOKEN = None
class DataProvider:
def __init__(self):
global API_TOKEN
if API_TOKEN is None:
API_TOKEN = get_token_from_database()
self.api_token = API_TOKEN
Error processing still omitted for brievety...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.