Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
5.8 kB
3
Indexable
from warnings import filterwarnings as warn_filterwarnings
warn_filterwarnings('ignore')
from models.hos_cart_details import hos_cart_details
#from models.hos_cart_details_by_username import hos_cart_details_username
#from models.hos_cart_details_by_businessid import hos_cart_details_businessid
#from models.hos_cart_details_by_status import hos_cart_details_status
from configparser import ConfigParser as conf_ConfigParser
from config.logger import configlogfile
from json import loads as json_loads
from json import dumps as json_dumps
from gc import collect as gc_collect
from sys import exc_info as sys_exc_info
from datetime import datetime,timedelta,timezone
from os import environ as os_environ
from os import path as os_path
from sys import path as sys_path
import pandas as pd
import ast
import json
import sys
import base64
from flask import Flask, jsonify
from flask import request
from flask import Response
import time


def getData(args, configvalues):  # UI Based Calling
    logging = configlogfile()
    __funcReturnAPICode = '0000'
    __funcReturnDesc = 'Successfully Completed the Process'
    eventdate = request.args.get('eventdate')
    business_id = request.args.get('businessid')
    username = request.args.get('username')
    status= request.args.get('status')
    startDate = request.args.get('startDate')
    logging.info(("startDate        : ",startDate))
    logging.info(("startDate        : ",type(startDate)))
    endDate = request.args.get('endDate')
    logging.info(("endDate        : ",type(endDate)))
    cartMapping = json_loads(configvalues.get('apiconfiguration', 'cartColumnMapping', raw=True))
    try:
        response_start_time=time.time()
        logging.info(("get cartDetails process started"))
        validkeys = json_loads(configvalues.get('apiconfiguration', 'validkeys', raw=True))
        logging.info(("Args.keys()      : %s" % set(list(args.keys()))))
        logging.info(("validkeys        : %s" % set(validkeys)))
        if 'businessid' in args.keys():
            results = hos_cart_details.objects.filter(hoscd_businessid=business_id).allow_filtering()
        elif 'eventdate' in args.keys():
            results = hos_cart_details.objects.filter(hoscd_event_date=eventdate)
        elif 'usernames' in args.keys():
            usernames = request.args.getlist('usernames')
            results = hos_cart_details.objects.filter(hoscd_username__in=list(usernames)).allow_filtering()
            print(results._select_query())
            logging.debug(results._select_query())
        elif 'username' in args.keys():
            results = hos_cart_details.objects.filter(hoscd_username=username).allow_filtering()
        elif 'username' in args.keys() and 'eventdate' in args.keys():
            results = hos_cart_details.objects.filter(hoscd_username=username,hoscd_event_date=eventdate).allow_filtering()
        elif 'status' in args.keys():
            results = hos_cart_details.objects.filter(hoscd_status=status).allow_filtering()
        elif 'username' in args.keys() and 'startDate' in args.keys() and 'endDate' in args.keys():
            results = hos_cart_details.objects.filter(hoscd_username=username,hoscd_event_date__gt=startDate, hoscd_event_date__lt=endDate).allow_filtering()
        elif 'businessid' in args.keys() and 'status' in args.keys():
            results = hos_cart_details.objects.filter(hoscd_businessid=business_id,hoscd_status=status).allow_filtering()
        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')
            end_date = datetime.strptime(endDate, '%Y-%m-%d')
            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(hoscd_event_date__in=dates_to_fetch)

            #results = hos_cart_details.objects.filter(hoscd_event_date>startDate,hoscd_event_date<endDate).allow_filtering()
        else:
            return ((["9003"], "Invalid Arguments passed to the API."))

        data = [{
            cartMapping['hoscd_event_date']: str(r.hoscd_event_date),
            cartMapping['hoscd_businessid']: r.hoscd_businessid,
            cartMapping['hoscd_buid']: r.hoscd_buid,
            cartMapping['hoscd_createdtime']: str(r.hoscd_createdtime),
            cartMapping['hoscd_opid']: r.hoscd_opid,
            cartMapping['hoscd_status']: r.hoscd_status,
            cartMapping['hoscd_type']: r.hoscd_type,
            cartMapping['hoscd_updatedtime']: str(r.hoscd_updatedtime),
            cartMapping['hoscd_username']: r.hoscd_username,
            cartMapping['hoscd_value']: base64.b64encode(r.hoscd_value).decode('utf-8'),
           cartMapping['hoscd_valuetype']: r.hoscd_valuetype
        } for r in results]
        logging.debug(results)
        logging.debug(data)
        response_end_time=time.time()
        elapsed_time=response_end_time-response_start_time
        count = len(data)
        response_data={
            "count":count,
            "api_response_time": elapsed_time,
            "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))))