【问题标题】:How to process a query before sending to Jinja2 template? App Engine如何在发送到 Jinja2 模板之前处理查询?应用引擎
【发布时间】:2017-11-09 10:48:43
【问题描述】:

我不知道如何在将查询结果发送到 Jinja2 以在浏览器上呈现之前对其进行处理。 我正在 Google App Engine for Python 上开发应用程序。

我将工作时间量存储在“日历”实体中,以秒为单位,这样我就可以对时间进行一些计算。我遇到的问题是如何修改查询结果,以便我将时间不是以秒为单位(整数)而是以 HH:MM(字符串)为单位传递给 Jinja2 html 文件

我的models.py文件如下:

            'calendars_list': calendars_list,

class Calendar(ndb.Model):
    wtd1 = ndb.IntegerProperty()  # Working seconds day 1
    wtd2 = ndb.IntegerProperty()  #  " 2
    wtd3 = ndb.IntegerProperty()  #  " 3
    wtd4 = ndb.IntegerProperty()  #  " 4
    wtd5 = ndb.IntegerProperty()  #  " 5
    wtd6 = ndb.IntegerProperty()  #  " 6
    wtd7 = ndb.IntegerProperty()  #  " 7

在主请求处理程序中,我得到查询(在定义祖先等之后)并且需要在浏览器中呈现之前将秒数更改为 HH:MM。

        calendars_query = models.Calendar.query(ancestor = get_calendars_key()).order(models.Calendar.calendar_id)
        calendars_list = calendars_query.fetch(10)
        # Now: convert working times per day (sec) to HH:MM
        for calendar in calendars_list:
            calendar.wtd1 = format_as_HHMM(calendar.wtd1)
            --> Gives an error: calendar.wtd1 needs to be an integer, can't be a string


        template_values = {
            'calendars_list': calendars_list,
        }    

        template = JINJA_ENVIRONMENT.get_template('calendars.html')
        self.response.write(template.render(template_values))

如上所示,当我修改 calendar.wtd1 元素以将其从 3600 更改为 01:00 时,我收到一个错误,因为它需要是一个整数。

有什么想法可以更改代码以便适当地处理查询结果吗?

谢谢!

【问题讨论】:

  • 能否分享一下“format_as_HHMM”函数的实现?
  • 嗨 Nicolas,我还没有实现这个功能。我可以在 python 中使用一些日期时间函数。目前我只有一个返回字符串“12:00”的存根。

标签: google-cloud-datastore jinja2 app-engine-ndb google-app-engine-python


【解决方案1】:

您的代码的问题是您尝试将一个不是整数的值分配给 ndb.IntegerProperty()。

替换

calendar.wtd1 = format_as_HHMM(calendar.wtd1) 

calendar.wtd1_HHMM = format_as_HHMM(calendar.wtd1) 

并在模板中使用 calendar.wtd1_HHMM,它可能会很好地工作。

编辑: 如果您希望在模板中将整数转换为 HH:mm 作为演示逻辑的一部分,您可以通过编写转换函数并将其注册为过滤器来轻松完成,如documentation - writing filters 中所述

当涉及到进行转换的函数时,你很幸运: Python: convert seconds to hh:mm:ss

【讨论】:

  • 您好 Arne,感谢您的反馈。我明白你在模板中使用 calendar.wtd1_HHMM 的意思。这意味着我需要为模板构建一个新的列表操作参数,我希望有一些日期转换功能可以解决问题。我会按照你的建议试试,谢谢!
猜你喜欢
  • 2018-07-15
  • 2015-08-22
  • 2018-05-04
  • 2011-12-12
  • 1970-01-01
  • 2015-05-19
  • 2017-03-05
  • 2016-08-23
  • 2014-03-24
相关资源
最近更新 更多