【问题标题】:Python | check if dict{} item is in list[]蟒蛇 |检查 dict{} 项目是否在 list[] 中
【发布时间】:2020-08-03 20:31:49
【问题描述】:
  • 尝试检查内存列表,plant_list[] 与来自 api 的 JSON 有效负载。

  • 如果传入有效负载的字典 nameplant_list 内部匹配,则 if 应该会触发。

  • 相反,我的脚本只返回 null

    请指出我的错误。

通过 api 调用发送的JSON 是:
{ "name":"swizz", "days": "7", "price": 2.00 }



源代码

from flask import Flask, request
from flask_restful import Api, Resource

app = Flask(__name__)
api = Api(app)


@app.route('/', methods=['GET', 'POST'])
def home():
    return 'Tiny'

plant_list = []
class Plant(Resource):
    def get(self, name):
        return {'Name':name}, 200

    def post(self, name):
        payload = request.get_json()
        for x in range(0, len(plant_list)):
            if payload['name'] == plant_list[x]['name']:
                return {'message': f'''Item {payload['name']} already stored in database.'''}
            else:
                plant_list.append(payload)
            return plant_list, 201


api.add_resource(Plant, '/plant/<string:name>')

if __name__ == '__main__':
    app.run(port=9004, debug=True)

【问题讨论】:

  • return plant_list, 201 的缩进是否正确?似乎它应该是不缩进的
  • plant_list 始终为空,并且您的 for 循环永远不会执行。此外,您在迭代列表时正在更改列表 - 这通常是个坏主意。
  • 这对您的null 问题没有帮助,但为了提高性能,我会将plant_list 更改为由name 键入的dict

标签: python python-3.x flask


【解决方案1】:

您可以简单地通过以下方式测试 dict 中的键:if key_name in my_dict:... 所以,if "price" in plant_list[x]:

【讨论】:

    【解决方案2】:

    您正在将 plant_list 设置为全局。如果你想在一个类中使用它,你应该在你的类的函数中定义它:

    plant_list = []
    class Plant(Resource):
        ....
        def post(self, name):
            global plant_list
            ....
    

    不知道为什么需要它作为全局变量。也许你想要:

    class Plant(Resource):
        plant_list = []
        ....
        def post(self, name):
            ....
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-11
      • 1970-01-01
      • 2019-10-30
      • 2022-01-25
      • 2021-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多