【问题标题】:Publish JSON data into a date based table using Flask Jinja2 template使用 Flask Jinja2 模板将 JSON 数据发布到基于日期的表中
【发布时间】:2021-05-21 03:45:41
【问题描述】:

我想要以表格格式在网页上发布 JSON 数据。我坚持验证 jinja 模板中的日期,因为缺少的日期很少,并且数据需要在只有数据可用的日期下发布。

我拥有的 JSON 数据: https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByPin?pincode=241301&date=21-05-2021

[我想要的页面视图][1] [1]:https://i.stack.imgur.com/OfVnT.png

我的代码:

<tbody>
  {% for center in centers %}
    <tr>                      
      <th scope="row">
        <address>
          {{ center['name'] }} <br>
          {{ center['address'] }}
        </address>
      </th>
      {% for date in dates %}
        {% if date == center["sessions"][dates.index(date)]["date"] %}
          <td>
            {{ center["sessions"][dates.index(date)]["available_capacity"] }} <br>
            {{ center["sessions"][dates.index(date)]["min_age_limit"] }} <br>
            {{ center["sessions"][dates.index(date)]["vaccine"] }} <br>
          </td>
        {% else %}
          <td>None</td>
        {% endif %}
      {% endfor %}
     </tr>
   {% endfor %}
 </tbody>

我有办法解决这个问题。我可以在新的 python 字典中预先格式化数据,而不是直接将原始 JSON 数据推送到 Jinja 模板,但我更想了解我们是否可以应用任何其他方法。

【问题讨论】:

    标签: python flask jinja2


    【解决方案1】:

    您不应该在模板中添加太多逻辑。

    这有几个原因:

    • 最佳实践。单一责任原则。
    • 良好的设计 - 应用程序逻辑独立于视图逻辑。
    • 防止难以辨认、难以理解和维护实施。
    • 为您的未来节省大量精力

    能够做某事,尤其是在 Python 之类的语言中,如果你愿意,它允许混合并变得非常深入和复杂(甚至丑陋),但这并不意味着你应该这样做。

    【讨论】:

    • 感谢您的建议,我会遵循最佳做法。
    猜你喜欢
    • 1970-01-01
    • 2011-03-13
    • 1970-01-01
    • 2020-09-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多