Python/Flask-如果x/y未返回true

Python/Flask-如果x/y未返回true,python,flask,Python,Flask,我有一个FlaskAPI端点,它返回消息JSON对象。每个都有一个名为recipients的字段,其中包含一个id整数列表。端点接受一个名为id的查询,然后应返回所查询的id位于收件人列表中的每条消息 @app.route('/api/uscorr/messages', methods=['GET']) def getMessages(): # Check that id was passed in the query if 'id' in request.args:

我有一个FlaskAPI端点,它返回消息JSON对象。每个都有一个名为
recipients
的字段,其中包含一个
id
整数列表。端点接受一个名为
id
的查询,然后应返回所查询的
id
位于
收件人列表中的每条消息

@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)
消息['recipients']中的语句
if-id:
永远不会解析为
true
,尽管从about-if打印出来的语句指示它应该这样做


我感觉自己错过了一些非常基本的东西。

您需要将
request.args['id']
转换为
int
。通常它是一个
字符串

id = int(request.args['id'])
但请先检查它是否为有效数字

request.args['id'].isdigit()
<> P>为了简化此转换,您还可以考虑使用<代码> WTFrass< /代码>。此处的文档:

它通常与WTF一起使用

一个简单的例子:

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

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

您需要将
request.args['id']
转换为
int
。通常它是一个
字符串

id = int(request.args['id'])
但请先检查它是否为有效数字

request.args['id'].isdigit()
<> P>为了简化此转换,您还可以考虑使用<代码> WTFrass< /代码>。此处的文档:

它通常与WTF一起使用

一个简单的例子:

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

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

您确定列表不是字符串列表吗?您正在尝试的是一个有效的python构造,因此这是我认为是aisde的唯一潜在原因,不建议使用
id
,因为它是一个内置关键字。直接输出显示在底部图片中,看起来像
int
对我来说请尝试打印
type(id),type(message['recipients'][0])
。我认为
id
的类型是string@YangHG完全正确我忘了将
id
转换为
int
,所以它是一个字符串。你确定列表不是字符串列表吗?您正在尝试的是一个有效的python构造,因此这是我认为是aisde的唯一潜在原因,不建议使用
id
,因为它是一个内置关键字。直接输出显示在底部图片中,看起来像
int
对我来说请尝试打印
type(id),type(message['recipients'][0])
。我认为
id
的类型是string@YangHG完全正确我忘了将
id
转换为
int
,所以它是一个字符串。