예제 #1
0
def get_user(user_id):
    """ GET user"""
    user = db.users.find_one({"_id": ObjectId(user_id)})
    if user is None:
        return jsonify({"success": False, "message": "User not found."}), 404

    return jsonify({"success": True, "user": clean_dict_helper(user)}), 200
예제 #2
0
def get_business_details(business_id):
    """ Get business details along with rating """

    business = db.dukaans.find_one({"_id": ObjectId(business_id)})
    if business is None:
        return jsonify({
            "success": False,
            "message": "Business not found."
        }), 404

    if len(business.get("categories", [])) > 0:
        business["categories"] = [
            db.categories.find_one({"_id": ObjectId(_id)})["name"]
            for _id in business["categories"]
        ]
    ratings = list(db.ratings.find({"business": str(business_id)}))
    if len(ratings) > 0:
        ratings_sum = sum([r["rating"] for r in ratings])
        business["avg_rating"] = round(
            float(ratings_sum) / float(len(ratings)), 1)
    else:
        business["avg_rating"] = 0.0

    for rating in ratings:
        rating["user_name"] = db.users.find_one(
            {"_id": ObjectId(rating["user"])})["name"]

    business["ratings"] = ratings
    business["total_ratings"] = len(ratings)
    return jsonify({"success": True, "business": clean_dict_helper(business)})
예제 #3
0
def get_business_by_city(city):
    businesses = list(
        db.dukaans.find({"city": {
            "$regex": city,
            "$options": "i"
        }}))
    # businesses = list(db.dukaans.find({"city": city}).limit(10))
    for business in businesses:
        if len(business.get("categories", [])) > 0:
            business["categories"] = [
                db.categories.find_one({"_id": ObjectId(_id)})["name"]
                for _id in business["categories"]
            ]
        ratings = list(
            db.ratings.find({"business": str(business["_id"])}, {"rating": 1}))
        if len(ratings) > 0:
            ratings_sum = sum([r["rating"] for r in ratings])
            business["avg_rating"] = round(
                float(ratings_sum) / float(len(ratings)), 1)
        else:
            business["avg_rating"] = 0.0
        business["total_ratings"] = len(ratings)
    return jsonify({
        "success": True,
        "businesses": clean_dict_helper(businesses)
    })
예제 #4
0
def add_rating():
    """Add a new rating"""
    try:
        payload = request.json
        # payload = change_case(payload, "lower")
        for required_key in rating_schema:
            if required_key not in payload.keys():
                return jsonify(
                    {"message": f"Missing {required_key} parameter"}), 400

        db_rating = db.ratings.find_one({
            "user": payload["user"],
            "business": payload["business"],
        })
        if db_rating is not None:
            db.ratings.update_one({'_id': db_rating['_id']},
                                  {'$set': {
                                      'rating': payload['rating']
                                  }},
                                  upsert=False)
            return jsonify({
                'success': True,
                'message': 'Rating updated successfully.'
            }), 201

        db.ratings.insert_one(payload)
        return jsonify({
            "success": True,
            "rating": clean_dict_helper(payload)
        }), 201

    except Exception as err:
        print("Error: ", str(err))
        print(sys.exc_info()[-1].tb_lineno)
예제 #5
0
def get_categories():
    """ List all categories """
    categories = list(db.categories.find({}))
    return jsonify({
        "success": True,
        "categories": clean_dict_helper(categories)
    })
예제 #6
0
def get_or_add_dukaan():
    """ Add a new business """
    if request.method == "POST":
        payload = request.json
        # payload = change_case(payload, "lower")
        business = db.dukaans.find_one({"name": payload["name"]})
        if business is not None:
            return (
                jsonify({
                    "success":
                    False,
                    "message":
                    "Business name already exists, Please choose another name.",
                }),
                400,
            )

        for required_key in business_schema:
            if required_key not in payload.keys():
                return jsonify(
                    {"message": f"Missing {required_key} parameter"}), 400

        db.dukaans.insert_one(payload)
        return jsonify({
            "success": True,
            "dukaan": clean_dict_helper(payload)
        }), 201

    dukaans = list(db.dukaans.find({}).limit(5))
    for dukaan in dukaans:
        if len(dukaan.get("categories", [])) > 0:
            dukaan["categories"] = [
                db.categories.find_one({"_id": ObjectId(_id)})["name"]
                for _id in dukaan["categories"]
            ]
        ratings = list(
            db.ratings.find({"business": str(dukaan["_id"])}, {"rating": 1}))
        if len(ratings) > 0:
            ratings_sum = sum([r["rating"] for r in ratings])
            dukaan["avg_rating"] = float(ratings_sum) / float(len(ratings))
        else:
            dukaan["avg_rating"] = 0.0

    return jsonify({"success": True, "dukaans": clean_dict_helper(dukaans)})
예제 #7
0
def add_student():
    student_schema = ["id", "name", "phone", "email", "subjects"]
    payload = request.json

    for required_key in student_schema:
        if required_key not in payload.keys():
            return jsonify({"message": "Missing {required_key} parameter"}), 400

    # db.student.insert_one(payload)
    # db.student.replace_one({"id":payload["id"]}, payload, upsert= True)
    db.student.replace_one({"email": payload["email"]}, payload, upsert=True)
    return jsonify({"success": True, "student": clean_dict_helper(payload)}), 201
예제 #8
0
def search(query):
    """ Search by business name """
    rgx = re.compile(".*{}.*".format(query),
                     re.IGNORECASE)  # compile the regex

    businesses = list(db.dukaans.find({"name": rgx}))
    if len(businesses) == 0:
        return jsonify({"success": False, "business": []}), 404

    return jsonify({
        "success": True,
        "business": clean_dict_helper(businesses)
    })
예제 #9
0
def get_student(stud_id):
    mongo_result = db.student.find_one({"id": int(stud_id)})

    print("DATA: ", mongo_result)
    # mongo_result = db.student.find_one({"id": 1})

    if mongo_result is None:
        return {
            "success": False,
            "message": "Student with ID: {} not found".format(stud_id),
            "data": mongo_result,
        }

    return jsonify({"success": True, "message": clean_dict_helper(mongo_result)}), 200
예제 #10
0
def add_user():
    """ Add a user"""
    payload = request.json
    for required_key in users_schema:
        if required_key not in payload.keys():
            return jsonify({"message":
                            f"Missing {required_key} parameter"}), 400

    user = db.users.find_one({"email": payload["email"]})
    if user is not None:
        return (
            jsonify({
                "success":
                False,
                "message":
                f'Duplicate email detected. User {payload["email"]} already exists.',
            }),
            400,
        )

    # payload = change_case(payload, "lower")
    db.users.insert_one(payload)
    return jsonify({"success": True, "user": clean_dict_helper(payload)}), 201
예제 #11
0
def get_rating(business_id):
    """ GET Business rating"""
    rating = list(
        db.ratings.aggregate([{
            "$group": {
                "_id": "$business",
                "pop": {
                    "$avg": "$rating"
                }
            }
        }]))
    if rating is None:
        return (
            jsonify({
                "success":
                False,
                "message":
                "Rating for business {} not found.".format(business_id),
            }),
            404,
        )
    print(rating)
    return jsonify({"success": True, "rating": clean_dict_helper(rating)})
예제 #12
0
def update_email():
    payload = request.json
    stud_id = payload["student_id"]
    stud_email = payload["student_email"]
    db.student.update_one({"id": stud_id}, {"$set": {"email": stud_email}})
    return jsonify({"success": True, "message": clean_dict_helper(payload)})
예제 #13
0
def update_user():
    payload = request.json
    student_id = payload["student_id"]
    student_name = payload["student_name"]
    db.student.update_one({"id": student_id}, {"$set": {"name": student_name}})
    return jsonify({"success": True, "message": clean_dict_helper(payload)})
예제 #14
0
def get_students():
    students = list(db.student.find())
    if len(students) == 0:
        return jsonify({"success": False, "students": []}), 200
    return jsonify({"success": True, "students": clean_dict_helper(students)}), 200