Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
5.0 kB
1
Indexable
Never
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 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")
            except ValueError:
                return ((["9003"], "Invalid createdtime format. Use yyyy-mm-dd. "))
            created_time=createdtime.date()
            results = cache_store_by_date.objects.filter(createdtime__date=created_time)
        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))))


above api is flask python api 
below is my cassandra tablw which it fetches from 
 businessid       | 4nIS5EwQG3a5
 valuetype        | OrderRequestContext
 key              | OrderRequestContext4nIS5EwQG3a5HOBDEFAULT
 buid             | DEFAULT
 createdtime      | 2022-12-06 19:47:37.554000+0530
 opid             | HOB
 status           | null
 type             | openapi.model.OrderRequestContext
 updatedtime      | 2022-12-06 19:47:37.554000+0530
 updatedtimestamp | null

https://172.16.177.58/HOBSAnalytics/dataservice/cacheStore?createdtime=2022-12-06
iam passing createdtime in above format but iam getting error as 
{
    "statusList": {
        "status": [
            {
                "statusCode": "9003",
                "statusType": "Warning",
                "statusDescription": "Invalid arguments passed to the API."
            }
        ]
    },
    "response": "Error - date doesn't map to a QueryOperator . Line No - 82 "
}