Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
68 views
in Technique[技术] by (71.8m points)

python - Duplicate field returned in postman using flask

I am working on a simple python app which fetches the reviews from users about different businesses, in this case I am trying to return a review and view it as an individual review however the "reviews" field seems to be duplicating but I have no idea where.

Here is the code for the app

from flask import Flask, request, jsonify, make_response
from pymongo import MongoClient
from bson import ObjectId
import json


class MyEncoder(json.JSONEncoder):

    def default(self, obj):
        if isinstance(obj, ObjectId):
            return str(obj)
        return super(MyEncoder, self).default(obj)

app = Flask(__name__)

client = MongoClient("mongodb://127.0.0.1:27017")
db = client.bizDB
businesses = db.biz
app.json_encoder = MyEncoder


with app.test_request_context():
    db.mycollection.insert_one({'a': 1})
    doc = db.mycollection.find_one({'a': 1})

    print(jsonify(doc).response)

@app.route("/api/v1.0/businesses", methods=["GET"])
def show_all_businesses():
    page_num, page_size = 1, 10
    if request.args.get("pn"):
        page_num = int(request.args.get("pn"))
    if request.args.get("ps"):
        page_size = int(request.args.get("ps"))
    page_start = page_size * (page_num - 1)

    data_to_return = []
    for business in businesses.find().skip(page_start).limit(page_size):
        business["_id"] = str(business["_id"])
        for review in business["reviews"]:
            review["_id"] = str(review["_id"])
        data_to_return.append(business)

    return make_response( jsonify( data_to_return ), 200 )


@app.route("/api/v1.0/businesses/<string:id>", methods=["GET"])
def show_one_business(id):
    business = businesses.find_one({"_id":ObjectId(id)})
    if business is not None:
        business["_id"] = str(business["_id"])
        for review in business["reviews"]:
            review["_id"] = str(review["_id"])
        return make_response ( jsonify ( business ), 200)
    else:
        return make_response (jsonify({ "error" : "Invalid Business ID" } ), 404)

@app.route("/api/v1.0/businesses", methods=["POST"])
def add_business():
    if "name" in request.form and "town" in request.form and "rating" in request.form:
        new_business = { "name" : request.form["name"],
                        "town" : request.form["town"],
                        "rating" : request.form["rating"],
                        "reviews" : {} 
                        }
        new_business_id = businesses.insert_one(new_business)
        new_business_link = "http://localhost:5000/api/v1.0/businesses/" + str(new_business_id.inserted_id)

        return make_response( jsonify( { "url" : new_business_link } ), 201 )
    else:
        return make_response ( jsonify( { "error" : "Missing form data" } ), 404 )


@app.route("/api/v1.0/businesses/<string:id>", methods=["PUT"])
def edit_business(id):
    if "name" in request.form and "town" in request.form and "rating" in request.form:
        result = businesses.update_one(
            {"_id" : ObjectId(id)},
            {
                "$set": { 
                    "name" : request.form["name"],
                    "town" : request.form["town"],
                    "rating" : request.form["rating"]
                }
            }
        )
        if result.matched_count == 1:
            edited_business_link = "http://localhost:5000/api/v1.0/businesses/" + id 
            return make_response( jsonify( { "url": edited_business_link } ), 200 )
        else:     
            return make_response ( jsonify( { "error" : "Invalid business ID" } ), 404 )
    else:
        return make_response ( jsonify( { "error" : "Missing form data" } ), 404 )

        
@app.route("/api/v1.0/businesses/<string:id>", methods=["DELETE"])
def delete_business(id):
    result = businesses.delete_one( { "_id" : ObjectId(id) })
    if result.deleted_count == 1:
        return make_response( jsonify( {} ), 200)
    else:
        return make_response ( jsonify( { "error" : "Invalid business ID" } ), 404 )



@app.route("/api/v1.0/businesses/<string:id>/reviews", methods=["POST"])
def add_new_review(id):
    new_review = { 
        "_id" : ObjectId(),
        "username" : request.form["username"],
        "comment" : request.form["comment"],
        "stars" : request.form["stars"]
    }
    businesses.update_one( { "_id" : ObjectId(id)} , {"$push" : { "reviews " : new_review}})
    new_review_link = "http://localhost:5000/api/v1.0/businesses/" + id + "/reviews/" + str(new_review["_id"])
    return make_response( jsonify( { "url" : new_review_link  } ), 201 )


@app.route("/api/v1.0/businesses/<string:id>/reviews", methods=["GET"])
def fetch_all_reviews(id):
    data_to_return = []
    business = businesses.find_one( {"_id" : ObjectId(id) }, { "reviews" : 1, "_id" : 0})
    for review in business["reviews"]:
        review["_id"] = str(review["_id"])
        data_to_return.append(review)
    return make_response( jsonify( data_to_return), 200 )


if __name__ == "__main__":
    app.run(debug=True)

Postman is returning a double review field which makes the returned field of review being empty when trying to select an individual one. double review in postman

question from:https://stackoverflow.com/questions/65546078/duplicate-field-returned-in-postman-using-flask

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can't have a "duplicate" field in the same object in MongoDB. On closer inspection, you can see one of the reviews fields has a space after it. You will need to tidy this up in the database and also in the code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...