Skip to content

Commit c061ce3

Browse files
authored
Merge pull request #9 from bunq/feature/bunq/tinker_python#8_sandbox_user_recreation_on_reset
Added error handling when Sandbox is reset
2 parents 81a2266 + 4af545b commit c061ce3

File tree

1 file changed

+22
-6
lines changed

1 file changed

+22
-6
lines changed

tinker/libs/bunq_lib.py

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import json
2+
from re import search
23
from os.path import isfile
4+
from os import remove
35
import socket
46

57
import requests
@@ -8,6 +10,7 @@
810
from bunq.sdk.context import ApiEnvironmentType
911
from bunq.sdk.context import BunqContext
1012
from bunq.sdk.exception import BunqException
13+
from bunq.sdk.exception import ForbiddenException
1114
from bunq.sdk.model.generated import endpoint
1215
from bunq.sdk.model.generated.object_ import Pointer, Amount, NotificationFilter
1316

@@ -41,7 +44,7 @@ def __init__(self, env):
4144
self.setup_context()
4245
self.setup_current_user()
4346

44-
def setup_context(self):
47+
def setup_context(self, reset_config_if_needed=True):
4548
if isfile(self.determine_bunq_conf_filename()):
4649
pass # Config is already present
4750
elif self.env == ApiEnvironmentType.SANDBOX:
@@ -52,18 +55,31 @@ def setup_context(self):
5255
else:
5356
raise BunqException(self._ERROR_COULD_NOT_DETIRMINE_CONF)
5457

55-
api_context = ApiContext.restore(self.determine_bunq_conf_filename())
56-
api_context.ensure_session_active()
57-
api_context.save(self.determine_bunq_conf_filename())
58+
try:
59+
api_context = ApiContext.restore(self.determine_bunq_conf_filename())
60+
api_context.ensure_session_active()
61+
api_context.save(self.determine_bunq_conf_filename())
5862

59-
BunqContext.load_api_context(api_context)
63+
BunqContext.load_api_context(api_context)
64+
except ForbiddenException as forbidden_exception:
65+
if reset_config_if_needed:
66+
self.__handle_forbidden_exception(forbidden_exception)
67+
else:
68+
raise forbidden_exception
6069

6170
def determine_bunq_conf_filename(self):
6271
if self.env == ApiEnvironmentType.PRODUCTION:
6372
return self._BUNQ_CONF_PRODUCTION
6473
else:
6574
return self._BUNQ_CONF_SANDBOX
6675

76+
def __handle_forbidden_exception(self, forbidden_exception):
77+
if self.env == ApiEnvironmentType.SANDBOX:
78+
remove(self.determine_bunq_conf_filename())
79+
self.setup_context(False)
80+
else:
81+
raise forbidden_exception
82+
6783
def setup_current_user(self):
6884
user = endpoint.User.get().value.get_referenced_object()
6985
if (isinstance(user, endpoint.UserPerson)
@@ -215,7 +231,7 @@ def generate_new_sandbox_user(self):
215231
:rtype: SandboxUser
216232
"""
217233

218-
url = "https://sandbox.public.api.bunq.com/v1/sandbox-user"
234+
url = ApiEnvironmentType.SANDBOX.uri_base + "sandbox-user"
219235

220236
headers = {
221237
'x-bunq-client-request-id': "uniqueness-is-required",

0 commit comments

Comments
 (0)