示例#1
0
def api_user_id(request):
    """Returns the API user id of the logged-in user"""
    user_id = 'not authenticated'
    get_current_user_api_url = '/users/current'
    #Here we can not get the user from obp-api side, so we use the django auth user id here.
    cache_key_django_user_id = request.session._session.get('_auth_user_id')
    cache_key = '{},{},{}'.format('api_user_id', get_current_user_api_url,
                                  cache_key_django_user_id)
    apicaches = None
    try:
        apicaches = cache.get(cache_key)
    except Exception as err:
        apicaches = None
    if not apicaches is None:
        return apicaches
    else:
        if request.user.is_authenticated:
            try:
                api = API(request.session.get('obp'))
                data = api.get('/users/current')
                user_id = data['user_id']
                apicaches = cache.set(cache_key, {'API_USER_ID': user_id})
                LOGGER.warning('The cache is setting try to api_user_id:')
                LOGGER.warning(
                    'The cache is setting key is: {}'.format(cache_key))
            except APIError as err:
                messages.error(request, err)
            except Exception as err:
                messages.error(request, err)
        return {'API_USER_ID': user_id}
示例#2
0
 def get_all_consumers(self):
     urlpath = '/management/consumers'
     api = API(self.request.session.get('obp'))
     cache_key = get_cache_key_for_current_call(self.request, urlpath)
     apicaches = None
     try:
         apicaches = cache.get(cache_key)
     except Exception as err:
         apicaches = None
     if not apicaches is None:
         apps_list = apicaches
     else:
         try:
             apps = api.get(urlpath)
             apps_list = apps["consumers"]
             cache.set(
                 cache_key, apps_list, 60 * 60
             )  # for the consumers we cache for 1 hour, consumers may be increased
             LOGGER.warning(
                 'The cache is setting, url is: {}'.format(urlpath))
             LOGGER.warning(
                 'The cache is setting key is: {}'.format(cache_key))
         except APIError as err:
             error_once_only(self.request, err)
         except Exception as err:
             error_once_only(self.request, 'Unknown Error. {}'.format(err))
     return apps_list
示例#3
0
def error_once_only(request, err):
    """
    Just add the error once
    :param request:
    :param err:
    :return:
    """
    LOGGER.exception('error_once_only - Error Message: {}'.format(err))
    storage = messages.get_messages(request)
    if str(err) not in [str(m.message) for m in storage]:
        messages.error(request, err)
示例#4
0
    def get_aggregate_metrics(self,
                              from_date,
                              to_date,
                              is_included_obp_apps,
                              only_show_api_explorer_metrics=False):
        """
        Gets the metrics from the API, using given parameters,
        There are different use cases, so we accept different parameters.
        only_show_api_explorer_metrics has the default value False, because it is just used for app = API_Explorer. 
        """
        try:
            api_calls_total = 0
            average_response_time = 0
            urlpath = '/management/aggregate-metrics'
            if only_show_api_explorer_metrics:
                urlpath = urlpath + '?from_date={}&to_date={}&app_name={}'.format(
                    from_date, to_date, API_EXPLORER_APP_NAME)
            elif ((not only_show_api_explorer_metrics)
                  and (not is_included_obp_apps)):
                urlpath = urlpath + '?from_date={}&to_date={}&exclude_app_names={}&exclude_implemented_by_partial_functions={}&exclude_url_pattern={}'.format(
                    from_date, to_date, ",".join(EXCLUDE_APPS),
                    ",".join(EXCLUDE_FUNCTIONS), ",".join(EXCLUDE_URL_PATTERN))
            else:
                urlpath = urlpath + '?from_date={}&to_date={}'.format(
                    from_date, to_date)
            cache_key = get_cache_key_for_current_call(self.request, urlpath)
            apicaches = None
            try:
                apicaches = cache.get(cache_key)
            except Exception as err:
                apicaches = None
            if not apicaches is None:
                metrics = apicaches
            else:
                api = API(self.request.session.get('obp'))
                metrics = api.get(urlpath)
                apicaches = cache.set(cache_key, metrics)
                LOGGER.warning(
                    'The cache is setting, url is: {}'.format(urlpath))
                LOGGER.warning(
                    'The cache is setting key is: {}'.format(cache_key))

            api_calls_total, average_calls_per_day, average_response_time = self.get_internal_api_call_metrics(
                api_calls_total, average_response_time, cache_key, from_date,
                metrics, to_date, urlpath)
            return api_calls_total, average_response_time, int(
                average_calls_per_day)
        except APIError as err:
            error_once_only(self.request, err)
        except Exception as err:
            error_once_only(self.request, 'Unknown Error. {}'.format(err))
示例#5
0
def api_username(request):
    """Returns the API username/email of the logged-in user"""
    nametodisplay = 'not authenticated'
    get_current_user_api_url = '/users/current'
    #Here we can not get the user from obp-api side, so we use the django auth user id here.
    cache_key_django_user_id = request.session._session.get('_auth_user_id')
    cache_key = '{},{},{}'.format('api_username', get_current_user_api_url,
                                  cache_key_django_user_id)
    apicaches = None
    try:
        apicaches = cache.get(cache_key)
    except Exception as err:
        apicaches = None
    if not apicaches is None:
        return apicaches
    else:
        if request.user.is_authenticated:
            try:
                api = API(request.session.get('obp'))
                data = api.get(get_current_user_api_url)
                username = data['username']
                email = data['email']
                provider = data['provider']
                if "google" in provider:
                    nametodisplay = email
                elif "yahoo" in provider:
                    nametodisplay = email
                elif "microsoft" in provider:
                    nametodisplay = email
                else:
                    nametodisplay = username
                apicaches = cache.set(cache_key,
                                      {'API_USERNAME': nametodisplay})
                LOGGER.warning('The cache is setting try to api_user_name:')
                LOGGER.warning(
                    'The cache is setting key is: {}'.format(cache_key))
            except APIError as err:
                messages.error(request, err)
            except Exception as err:
                messages.error(request, err)
        return {'API_USERNAME': nametodisplay}
示例#6
0
    def median_time_to_first_api_call(self, from_date, to_date):
        return 0  #TODO this cost too much time, do not use this at the moment.
        form = self.get_form()
        new_apps_list = []
        apps = []
        apps_list = self.get_all_consumers()

        for app in apps_list:
            created_date = datetime.datetime.strptime(app['created'],
                                                      '%Y-%m-%dT%H:%M:%SZ')
            created_date = created_date.strftime(API_DATEFORMAT)
            created_date = datetime.datetime.strptime(created_date,
                                                      API_DATEFORMAT)
            if created_date >= datetime.datetime.strptime(
                    from_date, API_DATEFORMAT):
                new_apps_list.append(app)

        times_to_first_call = []

        strfrom_date = datetime.datetime.strptime(from_date, API_DATEFORMAT)
        strto_date = datetime.datetime.strptime(to_date, API_DATEFORMAT)
        for app in new_apps_list:
            urlpath_metrics = '/management/metrics?from_date={}&to_date={}&consumer_id={}&sort_by={}&direction={}&limit={}'.format(
                from_date, to_date, app['consumer_id'], 'date', 'asc', '1')
            cache_key = get_cache_key_for_current_call(self.request,
                                                       urlpath_metrics)
            api = API(self.request.session.get('obp'))
            try:
                apicaches = None
                try:
                    apicaches = cache.get(cache_key)
                except Exception as err:
                    apicaches = None
                metrics = []
                if not apicaches is None:
                    metrics = apicaches
                else:
                    metrics = api.get(urlpath_metrics)

                    if metrics is not None and 'code' in metrics and metrics[
                            'code'] == 403:
                        error_once_only(self.request, metrics['message'])
                        if (metrics['message'].startswith('OBP-20006')):
                            break
                        metrics = []
                    else:
                        metrics = list(metrics['metrics'])
                        cache.set(cache_key, metrics)
                        LOGGER.warning(
                            'The cache is setting, url is: {}'.format(
                                urlpath_metrics))
                        LOGGER.warning(
                            'The cache is setting key is: {}'.format(
                                cache_key))
                if metrics:
                    time_difference = datetime.datetime.strptime(
                        metrics[0]['date'],
                        '%Y-%m-%dT%H:%M:%S.%fZ') - datetime.datetime.strptime(
                            app['created'], '%Y-%m-%dT%H:%M:%SZ')
                    times_to_first_call.append(time_difference.total_seconds())

            except APIError as err:
                error_once_only(self.request, err)
            except Exception as err:
                error_once_only(self.request, 'Unknown Error. {}'.format(err))

        if times_to_first_call:
            median = statistics.median(times_to_first_call)
            delta = datetime.timedelta(seconds=median)
        else:
            delta = 0

        return delta