in modular_api/index.py [0:0]
def index(path: str, allowed_commands=None, user_meta=None):
_trace_id = get_trace_id(tracer=tracer)
temp_files_list = []
try:
# TODO sort out relogin and remove
relogin_needed = __automated_relogin(request)
auth_type = request.headers.get('authorization')
if auth_type and auth_type.startswith('Basic'):
relogin_needed = False
if relogin_needed:
# if you are going to change exception message - please change
# correspond text in Modular-CLI
raise ModularApiUnauthorizedException(
'The provided token has expired due to updates in '
'commands meta. Please get a new token from \'/login\' '
'resource')
version_warning, error_response = __validate_cli_version(
_trace_id=_trace_id
)
if error_response:
return error_response
method = request.method
route_meta_mapping = generate_route_meta_mapping(
commands_meta=allowed_commands)
command_def = route_meta_mapping.get(path)
if not command_def:
raise ModularApiBadRequestException('Can not found requested '
'command')
request_body_raw = extract_and_convert_parameters(
request=request,
command_def=command_def
)
request_body_raw = validate_request(command=command_def,
req_params=request_body_raw,
method=method,
user_meta=user_meta)
secure_parameters = command_def.get('secure_parameters', [])
parameters, temp_files_list, _ = \
convert_api_params(
body=request_body_raw,
command_def=command_def,
secure_parameters=secure_parameters
)
_LOG.info('Request data: \npath={}\n'
'method={}'.format(path, method))
command_handler_name = command_def.get('handler')
route_path = command_def.get('route', {}).get('group_path')
group_path = '/'.join(route_path.split('/')[:-1])
correct_method = getattr(
MODULE_GROUP_GROUP_OBJECT_MAPPING[group_path],
command_handler_name)
# todo get username from user_meta of somewhere else, but
# not from header again.
username = username_from_jwt_token(
token_from_auth_header(request.headers.get('Authorization'))
)
if not username:
username, _ = request.auth
# saving username to thread-local storage
THREAD_LOCAL_STORAGE.set('modular_user', username)
curr_user = SP.user_service.describe_user(username)
# saving the meta.aux_data of user in the thread-local storage
modular_user_meta_aux = {}
if curr_user.meta:
meta_dict = curr_user.meta.as_dict()
aux_data = meta_dict.get(AUX_DATA)
modular_user_meta_aux = (
aux_data if isinstance(aux_data, dict) else {}
)
THREAD_LOCAL_STORAGE.set('modular_user_meta_aux', modular_user_meta_aux)
# hopefully, token will be here... otherwise 500, I mean, it must be
# here because the endpoint is authorized by token
try:
response = correct_method.main(
args=parameters,
standalone_mode=False,
obj={MODULAR_API_USERNAME: username}
)
except click.exceptions.UsageError as error:
# just in case something is not handled
return build_response(
_trace_id=_trace_id,
http_code=200, # means that click worked,
message=str(error)
)
# obj goes to click.Context. Other module CLI should use it to
# understand what user is making the request
response = json.loads(response)
_LOG.info(f'Obtained response {response} for {_trace_id} request')
content, code = process_response(response=response)
payload = {key.lower(): value for key, value in response.items()}
USAGE_SERVICE.save_stats(request=request, payload=payload) # TODO raises Value error sometimes
if content.get('warnings'):
if version_warning:
content['warnings'].extend(version_warning)
else:
content['warnings'] = version_warning
return build_response(_trace_id=_trace_id,
http_code=code,
content=content)
except Exception as e:
# TODO use _LOG.exception
_LOG.exception('Unexpected exception occurred')
code, content = build_exception_content(exception=e)
error_response = build_response(_trace_id=_trace_id,
http_code=code,
content=content)
USAGE_SERVICE.save_stats(request=request, payload=content)
return error_response
finally:
if temp_files_list:
for each_file in temp_files_list:
os.remove(each_file)