Search code examples
pythonmongodbflaskpymongoflask-pymongo

Strange equality error with PyMongo-flask


So I have this api endpoint:

@app.route("/subject", methods=["GET"])
def GET_subject():
    subject = request.args["subject"]
    page = int(request.args["page"])

    pagesize = 10
    subjectResults = db.subject.find()[pagesize*(page-1):pagesize*(page)]
    if subjectResults is "[]":
        return json.dumps({"page": page, "subject": subject, "subjectResults": bson.json_util.dumps(subjectResults)})
    else:
        return json.dumps({"error": "404"})

and when I run it, with no data in the database, it returns the error 404 message I put in. As you can tell, I'm using Flask and Flask-PyMongo for this.


Solution

  • With the is keyword, you are comparing identity of objects.

    In your case, you are checking if subjectResults is the same object as string literal "[]", which will always be False.

    See here for explanation on the is keyword.