Skip to content

Commit

Permalink
generated with codegen at box/box-codegen@d8b234c and spec at box/box…
Browse files Browse the repository at this point in the history
  • Loading branch information
box-sdk-build committed Aug 31, 2023
1 parent 46114b9 commit 569c8fc
Show file tree
Hide file tree
Showing 99 changed files with 2,738 additions and 2,738 deletions.
38 changes: 19 additions & 19 deletions box_sdk_gen/auth_schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,20 @@


class TokenRequestGrantType(str, Enum):
AUTHORIZATION_CODE = "authorization_code"
REFRESH_TOKEN = "refresh_token"
CLIENT_CREDENTIALS = "client_credentials"
AUTHORIZATION_CODE = 'authorization_code'
REFRESH_TOKEN = 'refresh_token'
CLIENT_CREDENTIALS = 'client_credentials'
URN_IETF_PARAMS_OAUTH_GRANT_TYPE_JWT_BEARER = (
"urn:ietf:params:oauth:grant-type:jwt-bearer"
'urn:ietf:params:oauth:grant-type:jwt-bearer'
)
URN_IETF_PARAMS_OAUTH_GRANT_TYPE_TOKEN_EXCHANGE = (
"urn:ietf:params:oauth:grant-type:token-exchange"
'urn:ietf:params:oauth:grant-type:token-exchange'
)


class TokenRequestBoxSubjectType(str, Enum):
ENTERPRISE = "enterprise"
USER = "user"
ENTERPRISE = 'enterprise'
USER = 'user'


class TokenRequest(BaseObject):
Expand Down Expand Up @@ -60,18 +60,18 @@ def __init__(


class FileScope(str, Enum):
ANNOTATION_EDIT = "annotation_edit"
ANNOTATION_VIEW_ALL = "annotation_view_all"
ANNOTATION_VIEW_SELF = "annotation_view_self"
BASE_EXPLORER = "base_explorer"
BASE_PICKER = "base_picker"
BASE_PREVIEW = "base_preview"
BASE_UPLOAD = "base_upload"
ITEM_DELETE = "item_delete"
ITEM_DOWNLOAD = "item_download"
ITEM_PREVIEW = "item_preview"
ITEM_RENAME = "item_rename"
ITEM_SHARE = "item_share"
ANNOTATION_EDIT = 'annotation_edit'
ANNOTATION_VIEW_ALL = 'annotation_view_all'
ANNOTATION_VIEW_SELF = 'annotation_view_self'
BASE_EXPLORER = 'base_explorer'
BASE_PICKER = 'base_picker'
BASE_PREVIEW = 'base_preview'
BASE_UPLOAD = 'base_upload'
ITEM_DELETE = 'item_delete'
ITEM_DOWNLOAD = 'item_download'
ITEM_PREVIEW = 'item_preview'
ITEM_RENAME = 'item_rename'
ITEM_SHARE = 'item_share'


class AccessToken(BaseObject):
Expand Down
8 changes: 4 additions & 4 deletions box_sdk_gen/base_object.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def __deserialize_list(cls, key, value, annotation: list):
@classmethod
def __deserialize_union(cls, key, value, annotation):
possible_types = get_args(annotation)
type_field_value = value.get("type", None) or value.get("skillCardType", None)
type_field_value = value.get('type', None) or value.get('skillCardType', None)

type = None
for i, possible_type in enumerate(possible_types):
Expand All @@ -85,7 +85,7 @@ def __deserialize_union(cls, key, value, annotation):
break

if not type:
print("Could not deserialize Union: ", annotation, "of value:", value)
print('Could not deserialize Union: ', annotation, 'of value:', value)

try:
return cls.__deserialize(key, value, type)
Expand All @@ -95,7 +95,7 @@ def __deserialize_union(cls, key, value, annotation):
@classmethod
def __deserialize_enum(cls, key, value, annotation):
try:
return getattr(annotation, value.upper().replace(" ", "_"))
return getattr(annotation, value.upper().replace(' ', '_'))
except Exception:
return value

Expand All @@ -107,4 +107,4 @@ def __deserialize_nested_type(cls, key, value, annotation):
return value

def __repr__(self) -> str:
return f"{self.__class__} {self.to_dict()}"
return f'{self.__class__} {self.to_dict()}'
6 changes: 3 additions & 3 deletions box_sdk_gen/ccg_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,11 +96,11 @@ def refresh(self, network_session: Optional[NetworkSession] = None) -> str:
)

response: FetchResponse = fetch(
"https://api.box.com/oauth2/token",
'https://api.box.com/oauth2/token',
FetchOptions(
method="POST",
method='POST',
body=urlencode(request_body.to_dict()),
headers={"content-type": "application/x-www-form-urlencoded"},
headers={'content-type': 'application/x-www-form-urlencoded'},
network_session=network_session,
),
)
Expand Down
60 changes: 30 additions & 30 deletions box_sdk_gen/fetch.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,11 @@
DEFAULT_MAX_ATTEMPTS = 5
_RETRY_RANDOMIZATION_FACTOR = 0.5
_RETRY_BASE_INTERVAL = 1
SDK_VERSION = "0.1.0"
USER_AGENT_HEADER = f"box-python-generated-sdk-{SDK_VERSION}"
SDK_VERSION = '0.1.0'
USER_AGENT_HEADER = f'box-python-generated-sdk-{SDK_VERSION}'
X_BOX_UA_HEADER = (
f"agent=box-python-generated-sdk/{SDK_VERSION}; "
f"env=python/{py_version.major}.{py_version.minor}.{py_version.micro}"
f'agent=box-python-generated-sdk/{SDK_VERSION}; '
f'env=python/{py_version.major}.{py_version.minor}.{py_version.micro}'
)


Expand All @@ -32,7 +32,7 @@ class MultipartItem:
part_name: str
body: str = None
file_stream: ByteStream = None
file_name: str = ""
file_name: str = ''
content_type: str = None


Expand Down Expand Up @@ -69,16 +69,16 @@ class APIException(Exception):
network_response: Optional[Response] = None

def __str__(self):
return "\n".join(
return '\n'.join(
(
f"Message: {self.message}",
f"Status: {self.status}",
f"Code: {self.code}",
f"Request ID: {self.request_id}",
f"Headers: {self.headers}",
f"URL: {self.url}",
f"Method: {self.method}",
f"Context Info: {self.context_info}",
f'Message: {self.message}',
f'Status: {self.status}',
f'Code: {self.code}',
f'Request ID: {self.request_id}',
f'Headers: {self.headers}',
f'URL: {self.url}',
f'Method: {self.method}',
f'Context Info: {self.context_info}',
)
)

Expand Down Expand Up @@ -109,7 +109,7 @@ def fetch(url: str, options: FetchOptions) -> FetchResponse:

while attempt_nr < max_attempts:
if response.ok:
if options.response_format == "binary":
if options.response_format == 'binary':
return FetchResponse(
status=response.status_code,
content=ResponseByteStream(
Expand All @@ -135,7 +135,7 @@ def fetch(url: str, options: FetchOptions) -> FetchResponse:
time.sleep(
__get_retry_after_time(
attempt_number=attempt_nr,
retry_after_header=response.get_header("Retry-After", None),
retry_after_header=response.get_header('Retry-After', None),
)
)

Expand All @@ -160,12 +160,12 @@ def fetch(url: str, options: FetchOptions) -> FetchResponse:
def __compose_headers_for_request(options: FetchOptions) -> Dict[str, str]:
headers = options.headers or {}
if options.auth:
headers["Authorization"] = (
f"Bearer {options.auth.retrieve_token(options.network_session)}"
headers['Authorization'] = (
f'Bearer {options.auth.retrieve_token(options.network_session)}'
)

headers["User-Agent"] = USER_AGENT_HEADER
headers["X-Box-UA"] = X_BOX_UA_HEADER
headers['User-Agent'] = USER_AGENT_HEADER
headers['X-Box-UA'] = X_BOX_UA_HEADER
return headers


Expand All @@ -180,7 +180,7 @@ def __make_request(
multipart_data,
attempt_nr,
) -> APIResponse:
if content_type == "multipart/form-data":
if content_type == 'multipart/form-data':
fields = OrderedDict()
for part in multipart_data:
if part.body:
Expand All @@ -190,14 +190,14 @@ def __make_request(
file_stream_position = file_stream.tell()
file_stream.seek(file_stream_position)
fields[part.part_name] = (
part.file_name or "",
part.file_name or '',
file_stream,
part.content_type,
)

multipart_stream = MultipartEncoder(fields)
body = multipart_stream
headers["Content-Type"] = multipart_stream.content_type
headers['Content-Type'] = multipart_stream.content_type

raised_exception = None
try:
Expand All @@ -216,11 +216,11 @@ def __make_request(
raised_exception = request_exc
network_response = None

if "EOF occurred in violation of protocol" in str(request_exc):
if 'EOF occurred in violation of protocol' in str(request_exc):
reauthentication_needed = True
elif any(
text in str(request_exc)
for text in ["Connection aborted", "Connection broken", "Connection reset"]
for text in ['Connection aborted', 'Connection broken', 'Connection reset']
):
reauthentication_needed = False
else:
Expand All @@ -242,13 +242,13 @@ def __raise_on_unsuccessful_request(network_response, url, method) -> None:
raise APIException(
status=network_response.status_code,
headers=network_response.headers,
code=response_json.get("code", None) or response_json.get("error", None),
message=response_json.get("message", None)
or response_json.get("error_description", None),
request_id=response_json.get("request_id", None),
code=response_json.get('code', None) or response_json.get('error', None),
message=response_json.get('message', None)
or response_json.get('error_description', None),
request_id=response_json.get('request_id', None),
url=url,
method=method,
context_info=response_json.get("context_info", None),
context_info=response_json.get('context_info', None),
network_response=network_response,
)

Expand Down
58 changes: 29 additions & 29 deletions box_sdk_gen/jwt_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def __init__(
private_key_passphrase: str,
enterprise_id: Optional[str] = None,
user_id: Optional[str] = None,
jwt_algorithm: str = "RS256",
jwt_algorithm: str = 'RS256',
**_kwargs
):
"""
Expand Down Expand Up @@ -85,7 +85,7 @@ def __init__(
@classmethod
def from_config_json_string(
cls, config_json_string: str, **kwargs: Any
) -> "JWTConfig":
) -> 'JWTConfig':
"""
Create an auth instance as defined by a string content of JSON file downloaded from the Box Developer Console.
See https://developer.box.com/en/guides/authentication/jwt/ for more information.
Expand All @@ -96,26 +96,26 @@ def from_config_json_string(
Auth instance configured as specified by the config dictionary.
"""
config_dict: dict = json.loads(config_json_string)
if "boxAppSettings" not in config_dict:
raise ValueError("boxAppSettings not present in configuration")
if 'boxAppSettings' not in config_dict:
raise ValueError('boxAppSettings not present in configuration')
return cls(
client_id=config_dict["boxAppSettings"]["clientID"],
client_secret=config_dict["boxAppSettings"]["clientSecret"],
enterprise_id=config_dict.get("enterpriseID", None),
jwt_key_id=config_dict["boxAppSettings"]["appAuth"].get(
"publicKeyID", None
client_id=config_dict['boxAppSettings']['clientID'],
client_secret=config_dict['boxAppSettings']['clientSecret'],
enterprise_id=config_dict.get('enterpriseID', None),
jwt_key_id=config_dict['boxAppSettings']['appAuth'].get(
'publicKeyID', None
),
private_key=config_dict["boxAppSettings"]["appAuth"].get(
"privateKey", None
private_key=config_dict['boxAppSettings']['appAuth'].get(
'privateKey', None
),
private_key_passphrase=config_dict["boxAppSettings"]["appAuth"].get(
"passphrase", None
private_key_passphrase=config_dict['boxAppSettings']['appAuth'].get(
'passphrase', None
),
**kwargs
)

@classmethod
def from_config_file(cls, config_file_path: str, **kwargs: Any) -> "JWTConfig":
def from_config_file(cls, config_file_path: str, **kwargs: Any) -> 'JWTConfig':
"""
Create an auth instance as defined by a JSON file downloaded from the Box Developer Console.
See https://developer.box.com/en/guides/authentication/jwt/ for more information.
Expand All @@ -125,7 +125,7 @@ def from_config_file(cls, config_file_path: str, **kwargs: Any) -> "JWTConfig":
:return:
Auth instance configured as specified by the JSON file.
"""
with open(config_file_path, encoding="utf-8") as config_file:
with open(config_file_path, encoding='utf-8') as config_file:
return cls.from_config_json_string(config_file.read(), **kwargs)


Expand All @@ -137,8 +137,8 @@ def __init__(self, config: JWTConfig):
"""
if None in (default_backend, serialization, jwt):
raise Exception(
"Missing dependencies required for JWTAuth. To install them use"
" command: `pip install box-sdk-gen[jwt]`"
'Missing dependencies required for JWTAuth. To install them use'
' command: `pip install box-sdk-gen[jwt]`'
)

self.config = config
Expand Down Expand Up @@ -175,25 +175,25 @@ def refresh(self, network_session: Optional[NetworkSession] = None) -> str:
jti_length = system_random.randint(16, 128)
ascii_alphabet = string.ascii_letters + string.digits
ascii_len = len(ascii_alphabet)
jti = "".join(
jti = ''.join(
ascii_alphabet[int(system_random.random() * ascii_len)]
for _ in range(jti_length)
)
now_time = datetime.utcnow()
now_plus_30 = now_time + timedelta(seconds=30)
assertion = jwt.encode(
{
"iss": self.config.client_id,
"sub": self.subject_id,
"box_sub_type": self.subject_type,
"aud": "https://api.box.com/oauth2/token",
"jti": jti,
"exp": int((now_plus_30 - datetime(1970, 1, 1)).total_seconds()),
'iss': self.config.client_id,
'sub': self.subject_id,
'box_sub_type': self.subject_type,
'aud': 'https://api.box.com/oauth2/token',
'jti': jti,
'exp': int((now_plus_30 - datetime(1970, 1, 1)).total_seconds()),
},
self._rsa_private_key,
algorithm=self.config.jwt_algorithm,
headers={
"kid": self.config.jwt_key_id,
'kid': self.config.jwt_key_id,
},
)

Expand All @@ -205,11 +205,11 @@ def refresh(self, network_session: Optional[NetworkSession] = None) -> str:
)

response: FetchResponse = fetch(
"https://api.box.com/oauth2/token",
'https://api.box.com/oauth2/token',
FetchOptions(
method="POST",
method='POST',
body=urlencode(request_body.to_dict()),
headers={"content-type": "application/x-www-form-urlencoded"},
headers={'content-type': 'application/x-www-form-urlencoded'},
network_session=network_session,
),
)
Expand Down Expand Up @@ -265,7 +265,7 @@ def _get_rsa_private_key(
@staticmethod
def _encode_str_ascii_or_raise(passphrase: str) -> bytes:
try:
return passphrase.encode("ascii")
return passphrase.encode('ascii')
except UnicodeError as unicode_error:
raise TypeError(
"private_key and private_key_passphrase must contain binary data"
Expand Down
Loading

0 comments on commit 569c8fc

Please sign in to comment.