For example, suppose I have an API based game server that processes player’s virtual game money from third party game bank (called it ‘bank’ in simple), players may play our game through my server, either win or lose game money, then post the ‘earn or lose’ result to the bank through their API. Now my server has 2 API : player_login and play_game, and my server would call bank API internally, in simple:
MyGame.views.py:
##############################################################################
### API player_login : player would enter my game from external bank website by calling the url : https://(my_game_server)/player_login?uid=..., then the bank would give my server a bank access token (for my server to call other bank API at later), also my server would generate a token for the player to access my server at later, also returns current balance to front-end to show
##############################################################################
def player_login(request):
uid = json.loads(request.body).get("uid")
bank_response_json = (API auth : pass 'uid' to bank to get user's current balance, also returns bank_token for my server to let my server call other bank API at later)
bank_token = bank_response_json.get("bank_token")
#start a new session associate with bank_token
token = apps.get_app_config("Core").START_LOGIN_SESSION(bank_token);
return JsonResoponse({
"token":token,
"balance":bank_response_json.get("balance")
});
##############################################################################
### API play_game : play some game that would win or lose some balance
##############################################################################
def play_game(request):
token = json.loads(request.body).get("token")
#check if token exists, if not, it raises exception
login_session = apps.get_app_config("Core").GET_LOGIN_SESSION(token);
bank_token = login_session["bank_token"];
win_balance = (some draw prize logic that would earn or lose balance)
bank_response_json = (API update_balance : pass 'bank_token','win_balance' to bank to update balance)
return JsonResoponse({
"token":token
"balance":bank_response_json.get("balance")
});
Now I would like to ask, in Django, is there any built-in functions like START_LOGIN_SESSION and GET_LOGIN_SESSION that can be used in the above scenario?
Now I just write the function by myself in scratch, which stores the login session in a variable login_session_dict that lives in a ‘Core’ app:
Core.apps.py
class CoreConfig(AppConfig):
login_session_dict = {}
.
.
.
def ready(self):
# regular job to remove expired tokens (5 minutes) to reduce memory use
def clean_expired_tokens():
time.sleep(self.get_config()["timeout"])
for token in list(self.login_session_dict):
if (datetime.now() - self.login_session_dict[token]["timestamp"]).total_seconds() >= 300:
self.login_session_dict.pop(token , None)
clean_expired_tokens()
_thread.start_new_thread(clean_expired_tokens,())
##############################################################################
### START_LOGIN_SESSION : generate a new token for new session with format {"bank_token":bank_token,"timestamp":timestamp} and then return the newly generated token
##############################################################################
def START_LOGIN_SESSION(self , bank_token):
#generate a new token for the player
token = uuid.uuid4()
while token in self.login_session_dict:
token = uuid.uuid4()
token = str(token)
self.login_session_dict[token] = {
"bank_token":bank_token,
"timestamp":datetime.now()
}
return token
##############################################################################
### GET_LOGIN_SESSION : get and check if current token is valid, if not, raise exception to stop the API
##############################################################################
def GET_LOGIN_SESSION(self , token):
#case that token not exists
if token not in self.login_session_dict:
raise Exception('token not exists')
#get related login_session
login_session = self.login_session_dict[token]
#check if token expired
if (datetime.now() - login_session["timestamp"]).total_seconds() >= 300:
raise Exception("login_session token expired")
#once the session is accessed, update session timestamp to avoid it becomes timeout
login_session["timestamp"] = datetime.now()
return login_session