Untitled

 avatar
unknown
plain_text
2 years ago
6.5 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,date
from cassandra.util import Date
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 dumps as json_dumps
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 'startDate' in args.keys() and 'endDate' in args.keys():
            try:
                startDate = datetime.strptime(startDate, '%Y-%m-%d')
                endDate = datetime.strptime(endDate, '%Y-%m-%d')
            except ValueError:
                return (["9003"], "Invalid startDate or endDate format. Use yyyy-mm-dd.")
            start_date = startDate.replace(hour=0, minute=0, second=0)
            end_date = endDate.replace(hour=23, minute=59, second=59)
            results = cache_store_by_date.objects.filter(createdtime__gte=start_date,
                                                         createdtime__lte=end_date).allow_filtering()
        elif 'startDate' in args.keys() and 'endDate' and 'username' in args.keys():
            try:
                startDate = datetime.strptime(startDate, '%Y-%m-%d')
                endDate = datetime.strptime(endDate, '%Y-%m-%d')
                username = username.strip('[]').split(',')
            except ValueError:
                return (["9003"], "Invalid startDate or endDate format. Use yyyy-mm-dd.")
            start_date = startDate.replace(hour=0, minute=0, second=0)
            end_date = endDate.replace(hour=23, minute=59, second=59)
            results = cache_store_by_username.objects.filter(createdtime__gte=start_date,
                                                         createdtime__lte=end_date,username__in=username).allow_filtering()
        elif 'createdtime' in args.keys():
            try:
                createdtime = datetime.strptime(createdtime, '%Y-%m-%d')
            except ValueError:
                return ((["9003"], "Invalid createdtime format. Use yyyy-mm-dd. "))
            start_date = createdtime.replace(hour=0, minute=0, second=0)
            end_date = createdtime.replace(hour=23, minute=59, second=59)

            results = cache_store_by_date.objects.filter(createdtime__gte=start_date,
                                                         createdtime__lte=end_date).allow_filtering()
        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)


        return "200",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))))

in the above api iam hitting the url like https://172.16.177.58/HOBSAnalytics/dataservice/cartDetails?startDate=2023-06-12&endDate=2023-06-12&username=[veera]
iam getting the data like 
[
    {
        "businessId": "002527a3-967d-46f0-8d28-bb416c04e67a",
        "valueType": "ConfiguredProductFromSession",
        "key": "ConfiguredProductFromSession002527a3-967d-56f0-8d28-bb416c04e67aHOBDEFAULT",
        "buID": "sdsdsd",
        "createdTime": "2023-06-13T06:03:33.772000",
        "opID": "HOB",
        "updatedTime": "2023-06-13T06:03:33.772000",
        "userName": "veera",
        "value": "eyJEZWxpdmVyeSBOb3RlcyI6ICJOb3RlcyAvIkROLyIifQ=="
    }
]
but i dont have any records with date 12 but still its getting the records with veera i want both conditions to be true
Editor is loading...