Exemple #1
0
def get_store_discounts(mongo, store_id):
    """ [GET] Return all the discounts that are associated with a store """

    discounts_doc = mongo.db.discounts.find()
    discount_json = {}
    response = {
        "success": False,
        "response": " "
    }
    if not discounts_doc:
        response['response'] = "No discounts at the moment."
        return response, 404

    for discount in discounts_doc:
        id = encode(discount['store_id'])[1:-1]
        if id == store_id:
            discount_json[encode(discount['_id'])[1:-1]] = \
                {
                    'store_id': store_id,
                    'data_expirare': discount['data_expirare'],
                    'procent': discount['procent'],
                    'gama_produs': discount['gama_produs']
                }

    return discount_json, 200
Exemple #2
0
    def to_json(self):
        final_json = {
            "_id": encode(self.id),
            "gama_produs": self.discount.gama_produs,
            "procent": self.discount.procent,
            "data_expirare": self.discount.data_expirare,
        }

        final_json["_id"] = final_json["_id"][1:-1]

        return final_json
def get_store_discounts(mongo, store_id):
    discounts_doc = mongo.db.discounts.find()
    discount_json = {}
    response = {"success": False, "response": " "}
    if not discounts_doc:
        response['response'] = "No discounts at the moment."
        return response, 404

    for discount in discounts_doc:
        id = encode(discount['store_id'])[1:-1]
        if id == store_id:
            discount_json = {
                '_id': encode(discount['_id'])[1:-1],
                'store_id': store_id,
                'data_expirare': discount['data_expirare'],
                'procent': discount['procent'],
                'gama_produs': discount['gama_produs']
            }

    return discount_json
def get_discounts_from_store(mongo, store_name):
    def update(email, discounts_array):
        # disc = mongo.db.discounts.find(discounts_array)
        # print(disc)
        user = mongo.db.users.find_one({"email": email})
        user_id = user['_id']
        user_to_update = user_mapper.from_json_to_object(user)

        if user_to_update.to_json()['discounts'] is not None:
            user_to_update.to_json()['discounts'] = list(
                filter(lambda x: not x['store_name'] == store_name,
                       user_to_update.to_json()['discounts']))
            for item in discounts_array:
                user_to_update.to_json()['discounts'].append(item)
        else:
            user_to_update.to_json()['discounts'] = discounts_array

        mongo.db.users.find_one_and_update({"_id": user_id},
                                           {"$set": user_to_update.to_json()})

        updated_user = UserEnhanced(user_to_update, user_id)

        return updated_user.to_json(), 200

    store_doc = mongo.db.stores.find_one({"store_name": store_name})
    if store_doc is None:
        response = {"success": False, "response": "Store doesn't exist"}
        return response, 404

    store_id = store_doc['_id']
    discounts = mongo.db.discounts.find({"store_id": str(store_id)})
    if discounts is None:
        response = {"success": False, "response": "No existing discount"}
        return response, 404
    discounts_to_send = []

    for discount in discounts:
        discounts_to_send.append({
            'discount_id': encode(discount['_id'])[1:-1],
            "store_name": store_name,
            "gama_produs": discount['gama_produs'],
            "procent": discount['procent'],
            'data_expirare': discount['data_expirare']
        })

    if 'user_email' not in session or 'user_id' not in session:
        response = {"success": False, "response": "Not logged in."}
        return response, 404

    print(session)
    email = dict(session)['user_email']

    update(email, discounts_to_send)
    return json.dumps(discounts_to_send), 200
def get_store(mongo, store_id):
    store_doc = mongo.db.stores.find_one({"_id": ObjectId(store_id)})
    response = {"success": False, "response": " "}
    if not store_doc:
        response['response'] = "No stores with the specified id."
        return response, 404

    store_json = {
        "store_name": store_doc['store_name'],
        "_id": encode(store_doc['_id'])
    }
    store_json["_id"] = store_json["_id"][1:-1]
    return store_json
def get_all_stores(mongo):
    store_doc = mongo.db.stores.find()
    response = {"success": False, "response": " "}
    if not store_doc:
        response['response'] = "No stores available."
        return response, 404

    store_json = {}
    for store in store_doc:
        store_json[encode(store['_id'])[1:-1]] = {
            "store_name": store['store_name'],
            'email': store['email']
        }
    return json.dumps(store_json)
def get_discount(mongo, discount_id):
    response = {"success": False, "response": " "}

    discount = mongo.db.discounts.find_one({"_id": ObjectId(discount_id)})
    if discount is None:
        response['response'] = "No existing discount"
        return response, 404
    discount_json = {
        "store_id": discount['store_id'],
        "gama_produs": discount['gama_produs'],
        "procent": discount['procent'],
        "_id": encode(discount['_id'])
    }
    discount_json["_id"] = discount_json["_id"][1:-1]
    return discount_json
Exemple #8
0
    def request(self, method, endpt, **kws):
        '''
        Low level method to perform API request: provide HTTP method and endpoint

        Optional args:
            _data = JSON document to be PUT (instead of **kws as dict)
            _headers = Extra headers to put on request (not useful?)

        NOTE: Any other arguments will end up as arguments to the API call itself.

        '''
        assert method in ('GET', 'PUT'), method

        # Compose the abs URL required
        url = urljoin(self.host, endpt)
        endpt = urlparse(url).path

        hdrs = {}

        if '_headers' in kws:
            # User may supply some headers? Probably not useful
            hdrs.update(kws.pop('_headers'))

        data = None
        if kws:
            assert '?' not in url, "Please don't mix keyword args and query string in URL"

            if method == 'GET':
                # encode as query args.
                url += '?' + urlencode(kws)
            else:
                # submit a JSON document, based on either the keyword args (made into a dict)
                # or whatever object is in "_data" argument
                logger.info("aa= %r" % kws.get('_data', kws))
                data = json_encoder.encode(kws.get('_data', kws))
                hdrs['Content-Type'] = 'application/json'

        # Show traffic.
        logger.info('%s %s' % (method, url))
        if method == 'PUT':
            logger.info(".. body: %r" % data)

        # we will retry rate-limited responses, so be prepared to retry here.
        while 1:
            if not endpt.startswith('/public'):
                # Almost always add AUTH headers
                hdrs.update(self._auth_headers(endpt))

            body, status = self.client.request(method, url, hdrs, data)

            # decode JSON
            body = json_decoder.decode(body)

            if status == 429 and 'wait_time' in body:
                # delay and retry
                logging.info("Rate limited: waiting %s seconds" %
                             body.wait_time)
                time.sleep(body.wait_time)
            else:
                break

        if status == 400:
            raise CKArgumentError(body)
        if status == 404:
            raise CKMissingError(body)
        elif status != 200:
            raise CKServerSideError(body)

        return body
Exemple #9
0
    def request(self, method, endpt, **kws):
        '''
        Low level method to perform API request: provide HTTP method and endpoint

        Optional args:
            _data = JSON document to be PUT (instead of **kws as dict)
            _headers = Extra headers to put on request (not useful?)

        NOTE: Any other arguments will end up as arguments to the API call itself.

        '''
        assert method in ('GET', 'PUT'), method

        # Compose the abs URL required
        url = urljoin(self.host, endpt)
        endpt = urlparse(url).path

        hdrs = {}

        if '_headers' in kws:
            # User may supply some headers? Probably not useful
            hdrs.update(kws.pop('_headers'))

        data = None
        if kws:
            assert '?' not in url, "Please don't mix keyword args and query string in URL"

            if method == 'GET':
                # encode as query args.
                url += '?' + urlencode(kws)
            else:
                # submit a JSON document, based on either the keyword args (made into a dict)
                # or whatever object is in "_data" argument
                logger.info("aa= %r" % kws.get('_data', kws))
                data = json_encoder.encode(kws.get('_data', kws))
                hdrs['Content-Type'] = 'application/json'

        # Show traffic.
        logger.info('%s %s' % (method, url))
        if method == 'PUT':
            logger.info(".. body: %r" % data)

        # we will retry rate-limited responses, so be prepared to retry here.
        while 1:
            if not endpt.startswith('/public'):
                # Almost always add AUTH headers
                hdrs.update(self._auth_headers(endpt))

            body, status = self.client.request(method, url, hdrs, data)

            if status == 504:
                raise CKGatewayTimeout()
        
            # decode JSON
            body = json_decoder.decode(body)

            if status == 429 and 'wait_time' in body:
                # delay and retry
                logging.info("Rate limited: waiting %s seconds" % body.wait_time)
                time.sleep(body.wait_time)
            else:
                break

        if status == 400:
            raise CKArgumentError(body)
        elif status == 404:
            raise CKMissingError(body)
        elif status != 200:
            raise CKServerSideError(body)

        return body