Flask and Jinja2: how to pass a method dynamically?

  flask, jinja2, python, python-3.x

I’m trying to create a homepage with a list of hyperlinks with numpy methods functions with sub-pages when one clicks on them. My idea would be that if I have a method, say, "multiplication", if I click on the "multiplication" link, given two arrays it will return the multiplication result. Homepage works, but I’m missing a step. Here is my webapp.py:

v = np.array([11, 12, 13, 14, 15])
v2 = np.array([11, 12, 13, 14, 15])
class Operation():
    def __init__(self, array1=v, array2=v2):
        self.array1 = array1
        self.array2 = array2
        print("Input arrays:", array1, "and", array2)

    def get_functions_names(self):
        listofmethods = dir(Operation)[-2:]
        return listofmethods

    def element_wise_addition(self):
        addition_result = self.array1 + self.array2
        return addition_result


app = Flask(__name__)
@app.route("/")
def homepage():
    names = Operation().get_functions_names()
    return render_template ("index.html",  names = names)


@app.route("/operations/<operation>")
def operations(operation):
    names = Operation().get_functions_names()
    return render_template("operations.html", names = names, Operation=Operation, operation=operation)

if __name__ == '__main__':
    app.run(debug=True)

index.html:

<body>
<h1>Operations</h1>
<ul>
        {% for name in names: %}
    <li><a href="./operations/{{name}}">{{name}}</a></li>
    {% endfor %}
    </ul>
</body>

and operations.html:

<body>


      <h1>Operations</h1>
<ul>
    {% for name in names: %}
        {% if name == operation: %}

        {% print(Operation().element_wise_addition()) %}

          {% endif %}
    {% endfor %}
</ul>




</body>

As I said, the homepage works but I don’t know how to pass the function relative to the link only, as I want to do it with many other functions.

Source: Python-3x Questions

LEAVE A COMMENT