Python/Flask – if x in y not returning true

Issue

I have a flask api endpoint that return message JSON objects. Each has a field called recipients which has a list of id integers. The endpoint takes one query which is id it should then return each message that the queried id is in the recipients list.

@app.route('/api/uscorr/messages', methods=['GET'])
def getMessages():

    # Check that id was passed in the query
    if 'id' in request.args:
        id = request.args['id']
    else:
        return "id is a mandatory query field"

    # Initialize blank results list
    results = []

    # Iterate through all messages in the database
    for message in messages:
        print("Looking for {} in list {}".format(id, message['recipients']))
        # Check if the queried id is in the list of message recipients
        if id in message['recipients']:
            print("Nothing makes it here")
            # Append current message to the results array as it is intended for the queried id
            results.append(message)

    # Check the number of results, return message if there were zero results
    if len(results) < 1:
        return "No match for found for the specified employee number"
    else:
        # Return the results list
        return jsonify(results)

The collection messages is a list of JSON message objects.

messages = [
  {
    "id": "9925bc3a-f0d4-44c4-adb6-0e7d4077cda7",
    "recipients": [
      7654674,
      432156,
      123456
    ],
    "subject": "labore eiusmod anim",
    "message": "Deserunt non magna mollit duis eiusmod dolor enim adipisicing cillum sunt incididunt veniam nulla. Veniam eiusmod consectetur aliquip nisi officia nisi labore in aute proident aliqua eiusmod Lorem tempor. Minim id voluptate incididunt culpa veniam et excepteur tempor fugiat ad adipisicing occaecat.",
    "priority": "Urgent",
    "from": "Veronica Davenport"
  }, ...

The statement if id in message['recipients']: never resolves as true despite the printed out from about if indicating that it should.

enter image description here

I get the gut feeling I missed something very basic.

Solution

You need convert request.args['id'] to int. Normally it is a string.

id = int(request.args['id'])

But please check if it is a valid digit first.

request.args['id'].isdigit()

To simplify this conversion, you could also consider using WTForms. Docs here: https://wtforms.readthedocs.io/en/2.3.x/

It often work with Flask-WTF together.

A simple example:

from flask.ext.wtf import Form
from wtforms import IntegerField
from wtforms.validators import InputRequired

class TestForm(Form):
    money = IntegerField('ID', validators=[InputRequired()])

Answered By – Yang HG

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published