从Flask模板中访问特定的字典键

时间:2017-01-06 22:05:06

标签: python json flask

我正在使用Python和Flask设置我的个人网站。对于博客部分,我正在从json文件中阅读我的博客文章,然后通过它来显示它们。一个模板。我正在读取python中的文件,如下所示:

@app.route('/blog')
def renderblog():
    filename = os.path.join(app.static_folder, 'blogs.json')
    with open(filename) as blog_file:
        data = json.load(blog_file)

    return render_template("blog.html", posts=data['posts'])

json文件的内容是:

{
  "posts": {
    "1": {
      "title": "Welcome",
      "author": "mikeres0",
      "date": "",
      "tags": "welcome,intro,outline",
      "content": "<p>Test content</p>",
      "hidden": "0"
    },
    "2": {
      "title": "Welcome",
      "author": "mikeres0",
      "date": "",      
      "tags": "",
      "content": "<p>Test content</p>",
      "hidden": "1"
    }
  }
}

在模板中,我显示的内容如下:

{% if posts %}
  {% for key, value in posts.items() %}
      {% for blogKey, blogValue in value.items() %}   
        {% if blogKey == 'title' %}
          {{ blogValue }}
        {% endif %}
        {% if blogKey == 'content' %}
          {{ blogValue|safe }}
        {% endif %}
      {% endfor %}
  {% endfor %}
{% endif %}

我遇到的问题是虽然json的格式是我喜欢的格式,但当文件被读入字典时,它并没有保留它。排序。在这种特定情况下,如何访问某些键值对?请在下面找到截图。 screenshot

2 个答案:

答案 0 :(得分:2)

所以,假设,基于你的例子你的字典&#34;键&#34;是存储为字符串的整数值,您可以这样做:

@app.route('/blog')
def renderblog():
    filename = os.path.join(app.static_folder, 'blogs.json')
    with open(filename) as blog_file:
        data = json.load(blog_file)

    order = [x for x in data['posts']]
    order.sort(key=lambda x: int(x))

    return render_template("blog.html", posts=data['posts'], order=order)

然后,在你的Jinja2模板中:

{% if posts %}
  {% for key in order %}
    {% for blogKey, blogValue in posts.key.items() %}   
      {% if blogKey == 'title' %}
        {{ blogValue }}
      {% endif %}
      {% if blogKey == 'content' %}
        {{ blogValue|safe }}
      {% endif %}
    {% endfor %}
  {% endfor %}
{% endif %}

在我看来,我使用的最佳实践(请在此挑战我)是使用字典列表,而不是迭代字典,这是没有订购的。因此,更理想的JSON结构将是这样的:

{
  "posts": [
    {
      "order": 1
      "title": "Welcome",
      "author": "mikeres0",
      "date": "",
      "tags": "welcome,intro,outline",
      "content": "<p>Test content</p>",
      "hidden": "0"
    },
    {
      "order": 2
      "title": "Welcome",
      "author": "mikeres0",
      "date": "",      
      "tags": "",
      "content": "<p>Test content</p>",
      "hidden": "1"
    }
  ]
}

你可以更简单地排序:

from operator import attrgetter

data['posts'].sort(key=attrgetter('order'))

答案 1 :(得分:0)

我在@PJ Santoro的答案中有点摆弄,但我决定采用另一种方法,将json加载到OrderedDict

import collections

@app.route('/blog')
def renderblog():
    filename = os.path.join(app.static_folder, 'blogs.json')
    with open(filename) as blog_file:
        data = json.load(blog_file, object_pairs_hook=collections.OrderedDict)

    return render_template("blog.html", posts=data['posts'])