コード例 #1
0
ファイル: dealsApi.py プロジェクト: hackercompany/perkkx_api
def get_all_deals_for_vendor(request, vendor):
    try:
        deal_query = {"vendor_id": int(vendor)}
        one_time_deals = list(db.one_time_deals.find(deal_query, deal_compact_filter))
        if "group" in request.GET:
            group_query_update(deal_query, request.GET["group"])

        deals = [d for d in db.deals.find(deal_query, deal_compact_filter) if deal_valid(d)]
        return HttpResponse(dumps({"data": deals, "total": len(deals), "one_time_deals": one_time_deals, "success": 1}))
    except Exception, e:
        return HttpResponse(dumps({"success": 0, "error": "Exception: " + str(e)}))
コード例 #2
0
def get_all_deals_for_vendor(request, vendor):
    try:
        deal_query = {'vendor_id': int(vendor)}
        one_time_deals = list(db.one_time_deals.find(deal_query, deal_compact_filter))
        if 'group' in request.GET:
            group_query_update(deal_query, request.GET['group'])

        deals = [d for d in db.deals.find(deal_query, deal_compact_filter)
                 if deal_valid(d)]
        return HttpResponse(dumps({"data": deals, "total": len(deals), "one_time_deals": one_time_deals, "success": 1}))
    except Exception, e:
        return HttpResponse(dumps({"success": 0, "error": "Exception: " + str(e)}))
コード例 #3
0
def get_deals(request, category):
    global db
    debug_message = ''
    debug2 = ''
    try:
        mCollection = db.merchants
        dCollection = db.deals
        data = []
        try:
            pages = int(request.GET['pages'])
        except:
            pages = 1
        if 'lat' in request.GET.keys() and 'lon' in request.GET.keys():
            lat = re.sub("[^0-9\.]", "", request.GET['lat'])
            lon = re.sub("[^0-9\.]", "", request.GET['lon'])
        else:
            lat = False
        if 'r' in request.GET.keys():
            r = int(request.GET['r'])
        else:
            r = False
        if 'open' in request.GET.keys():
            ope = True
        else:
            ope = False
        reverse = False
        if 'sort' in request.GET.keys():
            if 'rating' in request.GET['sort']:
                sort = 'rating'
                reverse = True
            elif 'price' in request.GET['sort']:
                sort = 'price'
            elif 'r' in request.GET['sort']:
                sort = 'distance'
            else:
                sort = 'distance'
        else:
            sort = 'distance'

        category = int(category)
        search = {"cat": category}
        if 'subcat' in request.GET.keys():
            search.update(
                {"subcat": {"$in": [int(x.replace("u", "").strip("'")) for x in request.GET['subcat'].split(",")]}})
        if 'ser' in request.GET.keys():
            search.update({"spec_event.title": {"$in": request.GET['ser'].split(",")}})
        if 'cuisine' in request.GET.keys():
            search.update({"cuisine": {"$in": request.GET['cuisine'].split(",")}})
        if 'mtype' in request.GET.keys():
            search.update({"massage.type": int(request.GET['mtype'])})
        if 'tag' in request.GET.keys():
            search.update({"icons": {"$in": request.GET['tag'].split(",")}})
        if 'vendor' in request.GET.keys():
            search.update(
                {"vendor_id": {"$in": [int(x.replace("u", "").strip("'")) for x in request.GET['vendor'].split(",")]}})
        if 'area' in request.GET.keys():
            search.update({"address.text": {
                "$in": [re.compile(x.replace("_", " "), re.IGNORECASE) for x in request.GET['area'].split(",")]}})
        if 'name' in request.GET.keys():
            search.update({"vendor_name": request.GET['name']})
        if 'type' in request.GET.keys():
            search.update({"type": {
                "$in": [re.compile(x.replace("_", " "), re.IGNORECASE) for x in request.GET['type'].split(",")]}})
        if 'rate' in request.GET.keys():
            rating = [float(int(x) - 0.1) for x in request.GET['rate'].split(",")]
            search.update({"rating": {"$gt": min(rating)}})
        if 'price' in request.GET.keys():
            low, high = request.GET['price'].split("-")
            low = int(low) - 1
            high = int(high) - 1
            search.update({"price": {"$gt": low, "$lt": high}})

        merchants = mCollection.find(search, merchant_filter)
        debug_message += "Count of merchants" + str(merchants.count()) + "\n"
        debug_message += "merchant query: " + str(search) + "\n"

        for mer in merchants:
            # --- Selecting a deal -------- #
            deal_query = {"vendor_id": mer['vendor_id']}

            if 'group' in request.GET and category != 5:
                group_query_update(deal_query, request.GET['group'])
            debug_message += "AND the query is :: " + json.dumps(deal_query)

            # Step 2, get the primary deal, now step 1
            deal_query.update({"deal_cat": "primary"})
            pdeal = dCollection.find_one(deal_query, deal_filter)  # Always false for cat 5

            if category != 5:
                deal_query.update({"deal_cat": "secondary"})
            else:
                deal_query.pop('deal_cat')
                deal_query.update({'rcodes.0': {"$exists": True}})

            secondaries = [s for s in dCollection.find(deal_query, deal_filter) if deal_valid(s)]
            if not deal_valid(pdeal):
                if len(secondaries) == 0:
                    continue
                pdeal = secondaries.pop(0)

            if len(secondaries) > 0:
                pdeal['second_deal'] = secondaries[0]['deal']

            '''
            if pdeal and deal_valid(pdeal):
                secondary = dCollection.find_one(deal_query, {"_id": False, "deal": True})
                if secondary:
                    pdeal['second_deal'] = secondary['deal']
            else:
                secondaries = [s for s in dCollection.find(deal_query, deal_filter) if deal_valid(s)]
                if len(secondaries) == 0:
                    continue
                pdeal = secondaries[0]
                if len(secondaries) > 1:
                    pdeal['second_deal'] = secondaries[1]['deal']
            '''

            # ----- Setup Merchant data ------ #
            mres = process_merchant(mer, long_version=False)  # Found in merchantApi
            if not mres:
                continue                # Skips the damn merchant

            if 'address' in mer and mer['address']['lat'] and mer['address']['lng']:
                if lat:
                    data_for_distance = {
                        "l1": float(lat),
                        "ln1": float(lon),
                        "l2": float(re.sub("[^0-9\.]", "", str(mer['address']['lat']))),
                        "ln2": float(re.sub("[^0-9\.]", "", str(mer['address']['lng'])))
                    }
                    mer.update({"distance": distance(data_for_distance)})
                else:
                    mer.update({"distance": False})
            else:
                mer.update({"distance": False})

            if pdeal:
                pdeal.update(mer)
                data.append(pdeal)

        start = (pages - 1) * 10
        end = start + 10

        ## God knows how to sort within lists, so we prepend the priority list (dynamic_deals) to the data list
        ## and hope for the best
        if end > len(data):
            end = len(data)
        if start > len(data):
            start = len(data) - 10
        if r:
            newlist = [x for x in data if x['distance'] < r]
        else:
            newlist = data
        if ope:
            delta = [x for x in newlist if x['open'] is True]
        else:
            delta = newlist
        newlist = sorted(delta, key=lambda k: k[sort] if k[sort] is not False else 100, reverse=reverse)

        open_now = [x for x in newlist if x.get('open', False)]
        closed_now = [x for x in newlist if not x.get('open', False)]

        final_list = open_now + closed_now
        res = {
            "total": len(newlist),
            "data": final_list[start:end],
            "page": pages
        }
        return HttpResponse(dumps(res), content_type="application/json")
    except Exception, e:
        raise
        return HttpResponse(dumps({"exception": "error : " + str(e)}), content_type="application/json")
コード例 #4
0
ファイル: dealsApi.py プロジェクト: hackercompany/perkkx_api
def get_deals(request, category):
    global db
    debug_message = ""
    debug2 = ""
    try:
        mCollection = db.merchants
        dCollection = db.deals
        data = []
        try:
            pages = int(request.GET["pages"])
        except:
            pages = 1
        if "lat" in request.GET.keys() and "lon" in request.GET.keys():
            lat = re.sub("[^0-9\.]", "", request.GET["lat"])
            lon = re.sub("[^0-9\.]", "", request.GET["lon"])
        else:
            lat = False
        if "r" in request.GET.keys():
            r = int(request.GET["r"])
        else:
            r = False
        if "open" in request.GET.keys():
            ope = True
        else:
            ope = False
        reverse = False
        if "sort" in request.GET.keys():
            if "rating" in request.GET["sort"]:
                sort = "rating"
                reverse = True
            elif "price" in request.GET["sort"]:
                sort = "price"
            elif "r" in request.GET["sort"]:
                sort = "distance"
            else:
                sort = "distance"
        else:
            sort = "distance"

        category = int(category)
        search = {"cat": category}
        if "subcat" in request.GET.keys():
            search.update(
                {"subcat": {"$in": [int(x.replace("u", "").strip("'")) for x in request.GET["subcat"].split(",")]}}
            )
        if "ser" in request.GET.keys():
            search.update({"spec_event.title": {"$in": request.GET["ser"].split(",")}})
        if "cuisine" in request.GET.keys():
            search.update({"cuisine": {"$in": request.GET["cuisine"].split(",")}})
        if "mtype" in request.GET.keys():
            search.update({"massage.type": int(request.GET["mtype"])})
        if "tag" in request.GET.keys():
            search.update({"icons": {"$in": request.GET["tag"].split(",")}})
        if "vendor" in request.GET.keys():
            search.update(
                {"vendor_id": {"$in": [int(x.replace("u", "").strip("'")) for x in request.GET["vendor"].split(",")]}}
            )
        if "area" in request.GET.keys():
            search.update(
                {
                    "address.text": {
                        "$in": [re.compile(x.replace("_", " "), re.IGNORECASE) for x in request.GET["area"].split(",")]
                    }
                }
            )
        if "name" in request.GET.keys():
            search.update({"vendor_name": request.GET["name"]})
        if "type" in request.GET.keys():
            search.update(
                {
                    "type": {
                        "$in": [re.compile(x.replace("_", " "), re.IGNORECASE) for x in request.GET["type"].split(",")]
                    }
                }
            )
        if "rate" in request.GET.keys():
            rating = [float(int(x) - 0.1) for x in request.GET["rate"].split(",")]
            search.update({"rating": {"$gt": min(rating)}})
        if "price" in request.GET.keys():
            low, high = request.GET["price"].split("-")
            low = int(low) - 1
            high = int(high) - 1
            search.update({"price": {"$gt": low, "$lt": high}})

        merchants = mCollection.find(search, merchant_filter)
        debug_message += "Count of merchants" + str(merchants.count()) + "\n"
        debug_message += "merchant query: " + str(search) + "\n"

        for mer in merchants:
            # --- Selecting a deal -------- #
            deal_query = {"vendor_id": mer["vendor_id"]}

            if "group" in request.GET and category != 5:
                group_query_update(deal_query, request.GET["group"])
            debug_message += "AND the query is :: " + json.dumps(deal_query)

            # Step 2, get the primary deal, now step 1
            deal_query.update({"deal_cat": "primary"})
            pdeal = dCollection.find_one(deal_query, deal_filter)  # Always false for cat 5

            if category != 5:
                deal_query.update({"deal_cat": "secondary"})
            else:
                deal_query.pop("deal_cat")
                deal_query.update({"rcodes.1": {"$exists": True}})

            if pdeal and deal_valid(pdeal):
                secondary = dCollection.find_one(deal_query, {"_id": False, "deal": True})
                if secondary:
                    pdeal["second_deal"] = secondary["deal"]
            else:
                secondaries = [s for s in dCollection.find(deal_query, deal_filter) if deal_valid(s)]
                if len(secondaries) == 0:
                    continue
                pdeal = secondaries[0]
                if len(secondaries) > 1:
                    pdeal["second_deal"] = secondaries[1]["deal"]

            # ----- Setup Merchant data ------ #
            process_merchant(mer, long_version=False)  # Found in merchantApi
            if "address" in mer and mer["address"]["lat"] and mer["address"]["lng"]:
                if lat:
                    data_for_distance = {
                        "l1": float(lat),
                        "ln1": float(lon),
                        "l2": float(re.sub("[^0-9\.]", "", str(mer["address"]["lat"]))),
                        "ln2": float(re.sub("[^0-9\.]", "", str(mer["address"]["lng"]))),
                    }
                    mer.update({"distance": distance(data_for_distance)})
                else:
                    mer.update({"distance": False})
            else:
                mer.update({"distance": False})

            if pdeal:
                pdeal.update(mer)
                data.append(pdeal)

        start = (pages - 1) * 10
        end = start + 10

        ## God knows how to sort within lists, so we prepend the priority list (dynamic_deals) to the data list
        ## and hope for the best
        if end > len(data):
            end = len(data)
        if start > len(data):
            start = len(data) - 10
        if r:
            newlist = [x for x in data if x["distance"] < r]
        else:
            newlist = data
        if ope:
            delta = [x for x in newlist if x["open"] is True]
        else:
            delta = newlist
        newlist = sorted(delta, key=lambda k: k[sort] if k[sort] is not False else 100, reverse=reverse)
        res = {"total": len(newlist), "data": newlist[start:end], "page": pages, "debug": debug_message}
        return HttpResponse(dumps(res), content_type="application/json")
    except Exception, e:
        return HttpResponse(dumps({"exception": "error : " + str(e)}), content_type="application/json")