【问题标题】:How to Query dictionary based on a criteria in flask如何根据烧瓶中的条件查询字典
【发布时间】:2019-08-31 15:54:56
【问题描述】:

我刚开始玩python和flask :)

我有以下包含字典的烧瓶应用程序,我正在尝试根据条件从数组中查询。例如:如果名称与 john 匹配,则显示他的 displayName。

app.py:


from flask import Flask, render_template, Response, request, send_from_directory
from flask import request
import subprocess
import json
import shlex
import socket
import time

app = Flask(__name__)

actors = {
  "actorname":[
  {
    "displayName": "john wick",
    "name": "john"
  },
  {
    "displayName": "george clooney",
    "name": "george"
  },
  {
    "displayName": "brad pitt",
    "name": "brad"
  }
  ]
 }


@app.route('/actors')
def theactors():

     return render_template('actors.html', actors=actors)

if __name__ == '__main__':
  app.run(host='127.0.0.1', port=5000, debug=True)

在我的actors.html中

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

        <title> Holywood actors </title>

</head>
<body>
    <h1> the display name for the actor {{actors.actorname[0].name}} is  {{actors.actorname[0].displayName}}</h1>

</body>
</html>

因此,我不想指定位置 0“actors.actorname[0].displayName”,而是添加一个条件来搜索数组中的所有 name=john 并显示 displayName。

【问题讨论】:

    标签: python python-3.x flask jinja2


    【解决方案1】:

    使用Python的过滤功能,可以达到想要的效果。例如,请看下面的代码:

    list(filter(lambda x:x['name']=='john',actors["actorname"]))
    

    【讨论】:

    • 对不起,我是 python 新手,我该在哪里添加那行?在 html 代码中不可能吗?
    【解决方案2】:

    它非常简单。修改你的 app.py 为:

        @app.route('/actors')
        def theactors():
            data = list(filter(lambda                                         
            x:x['name']=='john',actors["actorname"]))
            return render_template('actors.html', actors=data)
    

    那么,你的模板文件应该是这样的:

        {{ actors }}
    

    【讨论】:

    • 这行得通,但它给了我完整的输出 ``` [{'displayName': 'John wick', 'name': 'john'}] ``` 目标是只返回值对于 displayName == 约翰。我还尝试在 html 中显示 {{actors.displayName}} 但没有返回任何内容
    • {{ actor[0].displayName }}
    • actors 是一个列表,所以你必须对其进行索引以获取 0 处的第一个元素,然后获取属性 displayName
    猜你喜欢
    • 2020-10-21
    • 1970-01-01
    • 2021-04-09
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多