Skip to content

Functionality to refresh token after a set amount of time #431

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: dev
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion mssql/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,26 @@
EDITION_AZURE_SQL_DB = 5
EDITION_AZURE_SQL_MANAGED_INSTANCE = 8


class BaseTokenManager:
invalidate_seconds = 600 # 10 minutes

_token = None
last_token_creation = datetime.datetime.now()

@property
def token(self):
td = datetime.timedelta(seconds=self.invalidate_seconds)
now = datetime.datetime.now()
if self._token is None or self.last_token_creation < now - td:
self._token = self.get_token()
self.last_token_creation = datetime.datetime.now()
return self._token

def get_token(self):
raise NotImplementedError("This method should be implemented!")


def encode_connection_string(fields):
"""Encode dictionary of keys and values as an ODBC connection String.

Expand Down Expand Up @@ -360,8 +380,13 @@ def get_new_connection(self, conn_params):
'timeout': timeout,
}
if 'TOKEN' in conn_params:
token = conn_params['TOKEN']
if isinstance(token, BaseTokenManager):
token_obj = token
token = token_obj.token

args['attrs_before'] = {
1256: prepare_token_for_odbc(conn_params['TOKEN'])
1256: prepare_token_for_odbc(token)
}
while conn is None:
try:
Expand Down