首页 > 解决方案 > 模态视图中的计算繁重方法

问题描述

我有一个简单的Person类,它有一个name属性和一些计算量大的方法,称为computationally_heavy_method

class Person:
    def __init__(self, name: str):
        self.name = name
    def __repr__(self) -> str:
        return self.name
    def computationally_heavy_method(self) -> str:
        # do lots of stuff and then return the result.
        return ''

我有很多实例Person

people = [Person(name='Alex')] * 1000

我将其传递给 jinja 模板,如下所示:

from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
    return render_template('index.html', people=people)

index.html 文件看起来像这样:

<!DOCTYPE html>
<html>
    <body>
        {% for person in people %}
            <button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bd-example-modal-lg">
                {{ person | safe }}
            </button>
            <div class="modal fade bd-example-modal-lg" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
                <div class="modal-dialog modal-lg" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="myLargeModalLabel">{{ person }}</h5>
                        </div>
                        <div class="modal-body" style="background-color: lightblue;">
                            {{ person.computationally_heavy_method() }}
                        </div>
                    </div>
                </div>
            </div>
        {% endfor %}
    </body>
<html>

所以基本上我有一个代表人的按钮列表,当你点击它时会显示一个模式视图。

但是,由于对computationally_heavy_method方法的重复调用,模态视图的计算量非常大。

有没有办法在需要时(即实际按下按钮时)而不是为所有 1000 个Person实例制作模态视图?

感谢您在这里的任何帮助。

标签: pythonclassflaskjinja2

解决方案


推荐阅读