Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
4.9 kB
2
Indexable
from models.cache_store import cache_store
from models.cache_store_by_username import cache_store_by_username
from models.cache_store_by_date import cache_store_by_date
from models.indexes import indexes
from models.columns import columns as tablecolumns
from datetime import datetime, timedelta, timezone
from dateutil.relativedelta import relativedelta
from pandas.io.json import json_normalize
import json
from config.logger import configlogfile
import base64
from flask import jsonify, make_response
import pandas as pd
import sys
import gc
import uuid
import pytz
from flask import request
from flask import Response
from json import loads as json_loads
from gc import collect as gc_collect
from dateutil.parser import parse



"""
This function is used to fetch cache details based on valueType and key
"""


def getData(args, configvalues):  # UI Based Calling
    logging = configlogfile()
    __funcReturnAPICode = '0000'
    __funcReturnDesc = 'Successfully Completed the Process'
    businessid=request.args.get('businessid')
    createdtime=request.args.get('createdtime')
    username = request.args.get('username')
    startDate = request.args.get('startDate')
    endDate = request.args.get('endDate')

    columnMapping = json_loads(configvalues.get('apiconfiguration', 'columnMapping', raw=True))
    try:
        logging.info(("process started"))
        validArguments = json_loads(configvalues.get('apiconfiguration', 'validArguments', raw=True))
        logging.info(("Args.keys()      : %s" % set(list(args.keys()))))
        logging.info(("validArguments        : %s" % set(validArguments)))
        if 'businessid' in args.keys():
            results = cache_store.objects.filter(businessid=businessid)
        elif 'username' in args.keys():
            username = username.strip('[]').split(',')
            results = cache_store_by_username.objects.filter(username__in=username)
        elif 'createdtime' in args.keys():
            try:
                createdtime = datetime.strptime(createdtime, "%Y-%m-%d %H:%M:%S.%f%z")
            except ValueError:
                createdtime = parse(createdtime)
            results = cache_store_by_date.objects.filter(createdtime=createdtime)
        elif 'startDate' in args.keys() and 'endDate' in args.keys():
            # __lt and __gt are used to perform less than and greater than operation
            start_date = datetime.strptime(startDate, "%Y-%m-%d %H:%M:%S.%f%z")
            end_date = datetime.strptime(endDate, "%Y-%m-%d %H:%M:%S.%f%z")
            dates_to_fetch = []
            current_date = start_date
            while current_date <= end_date:
                dates_to_fetch.append(current_date)
                current_date += timedelta(days=1)
            results = hos_cart_details.objects.filter(createdtime__in=dates_to_fetch)

        else:
            return ((["9003"], "Invalid Arguments passed to the API."))
        page = request.args.get('page',1)
        limit = request.args.get('limit',20)
        if page is not None and limit is not None:
            try:
                page=int(page)
                limit=int(limit)
            except ValueError:
                return("400" "both page and limit must be integers")
        offset = (page - 1) * limit if page is not None and limit is not None else 0
        paginated_res=results[offset:offset+limit]


        data = [{
            columnMapping['businessid']: r.businessid,
            columnMapping['valuetype']: r.valuetype,
            columnMapping['key']: str(r.key),
            columnMapping['buid']: r.buid,
            columnMapping['createdtime']: r.createdtime.isoformat(),
            columnMapping['opid']: r.opid,
            columnMapping['updatedtime']: r.updatedtime.isoformat(),
            columnMapping['username']: r.username,
            columnMapping['value']: base64.b64encode(r.value).decode('utf-8'),
           columnMapping['valuetype']: r.valuetype
        } for r in paginated_res]
        logging.debug(results)
        logging.debug(data)
        response_data={
            "data":data
        }

        return ("200",(response_data))




    except Exception as e:
        gc_collect()
        logging.error("Error - {} . Line No - {} ".format(str(e), str(sys.exc_info()[-1].tb_lineno)))
        # return (("500", "Technical exception"))
        return ((["9003"], "Error - {} . Line No - {} ".format(str(e), str(sys.exc_info()[-1].tb_lineno))))





i have above api and in createdtime iam fetching time..actually in my database i have createdtime in this format  updatedtime      | 2022-12-06 19:47:37.554000+0530 but in my api i will passing only yyyy-mm-dd https://172.16.177.58/HOBSAnalytics/dataservice/cacheStore?createdtime=2022-12-06 like this can you modify pls