python - 在 Jinja2 模板中访问类方法

标签 python python-3.x flask jinja2

我在后端使用 Flask 应用程序,它应该使用 Jinja2 模板内的循环在前端呈现 SKU(库存单位)代码列表。 SKU分类如下:

class SKU:
"""Class to hold SKU data returned from the database."""

def __init__(self, sku, scanned_at, actual_count, expected_count):
    """Initialize the SKU class with relevant attributes."""
    self.sku = str(sku)
    self.scanned_at = str(scanned_at)
    self.actual_count = int(actual_count)
    self.expected_count = int(expected_count)

def get_progress(self):
    """Get the SKU production progress as a percentage."""
    return ((self.actual_count / self.expected_count) *
            100 if self.expected_count != 0 else 0)

我有一个方法 get_all_skus_today() 返回数据库中今天日期的所有行,作为 SKU 对象的列表。当有人使用以下路由访问 /skus 时,我想呈现它:

@app.route("/skus")
def skus():
    """Get all SKUs for the day and render the skus.html template."""
    skus = get_all_skus_today()
    return render_template("skus.html", skus=skus)

问题是我要显示进度值,也就是函数get_progress()的返回值,不是Class属性,而是方法。我想做这样的事情:

{% for sku_row in skus %}
    {{ sku_row.sku }}
    {{ sku_row.get_progress }}
{% endfor %}

但这行不通。我想避免循环遍历 SKU 对象列表并将它们转换为元组,然后传递给 render_template 函数(这是我之前所做的)。

非常感谢任何帮助 - 如果您需要任何进一步的说明,请告诉我。

最佳答案

您可以创建一个额外的类来加载和处理来自数据库的信息,并创建一个 Sku 对象列表:

import sqlite3
class _Sku:
   def __init__(self, row):
     self.__dict__ = dict(zip(row, ['_sku', 'scanned_at', 'actual_count', 'expected_count']))
   @property
   def sku(self):
      return str(self._sku)
   @property
   def get_progress(self):
     return ((int(self.actual_count) / int(self.expected_count)) *
        100 if int(self.expected_count) != 0 else 0)

class Sku:
  def __init__(self, _listing):
    self.all_vals = [_Sku(i) for i in _listing]
  def __iter__(self):
    yield from self.all_vals
  @classmethod
  def create_skus(cls, _filename='somefilename.db'):
    #if so desired, you can replace query below with your own
    return cls(sqlite3.connect(_filename).cursor().execute("SELECT scanned, actual, expected FROM skus"))

然后,在应用程序中:

@app.route("/skus")
def skus():
  """Get all SKUs for the day and render the skus.html template."""
   return render_template("skus.html", skus=Sku.create_skus())

现在,上面的代码将启用您的原始模板:

{% for sku_row in skus %}
   {{ sku_row.sku }}
   {{ sku_row.get_progress }}
{% endfor %}

关于python - 在 Jinja2 模板中访问类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52594285/

相关文章:

python - Flask 模型 .save() 引发 TypeError : _validate() missing 1 required positional argument: 'value'

python - python 内存不足错误的解决方法是什么?

python - 获取给定日期的 gps 周数

python - 如何继承__del__函数

python - 如何在虚拟环境中使用 pip nodjs 安装 jupyterlab-plotly labextension?

python - flask ,FlaskSocketIO - 运行时错误 : Cannot obtain socket from WSGI environment

python-3.x - 如何在Python中查找两个时间戳之间的差异?

Python - 计算来自 txt 文件的标签的行之间的时间差

python - 为什么索引错误: index 1 is out of bounds for axis 0 with size 1

python - 在单个 View 方法中接受多种请求类型的更好方法?