如何在不使用 html 按钮更改 route/outside 路由的情况下 运行 在 Flask 中实现 python 功能?

How to run a python function in flask without changing the route/outside the route with html button?

我正在开发一个 UI,我应该在其中 运行 一个带有 HTML 按钮的 python 脚本。我正在使用烧瓶。

我的 UI 中有两个“洞察引擎”按钮。一个在顶部的导航栏中,另一个是带有上传图标的蓝色简单按钮。

代码如下:

  1. 烧瓶 main.py

from flask import Flask, render_template
from flask_bootstrap import Bootstrap
from flask_nav import Nav
from flask_nav.elements import *
from dominate.tags import img

import config
from doc_parser import get_text_from_pdf
topbar = Navbar(
                View('Reports', 'get_reports'),
                View('Insight Engine', 'get_engine')
                )

nav = Nav()
nav.register_element('top', topbar)

app = Flask(__name__)
Bootstrap(app)

@app.route('/', methods=['GET'])
def index():
    return(render_template('index.html'))

@app.route('/reports', methods=["GET"])
def get_reports():
    return(render_template('reports.html'))

@app.route('/engine', methods=["GET"])
def get_engine():

    get_text_from_pdf(config.doc_path) #Here I am calling python function

    return(render_template('engine.html'))


nav.init_app(app)


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

  1. 洞察引擎按钮(蓝色一个):
<a href="/engine" class="upload1"  style="padding: 0.8%; border-radius: 5px; width: 12%;"><i class="fa fa-upload"></i><span style="display:inline-block; width: 5px;"></span> Insight Engine</a>

问题:我点击顶部按钮或蓝色按钮,都是运行宁我的python脚本。我知道这是因为我给两者都提供了相同的路线。但我想要的是,当我单击顶部按钮时,它会在没有 运行ning python 脚本的情况下转到洞察引擎导航选项卡。但是当我点击蓝色按钮时,它会 运行 python 脚本,然后它会转到 insight engine 导航选项卡。

简单来说,我想使用两个 diff 函数去同一条路线 (/engine)。一种不会 运行 我的 python 脚本,另一种会 运行 我的 python 脚本。

如何操作?

如果你想使用相同的路线,你需要以某种方式传递信息,它是否 运行 脚本。您可以使用 query string.

来实现
@app.route("/engine", methods=["GET"])
def get_engine():
    use_script = request.args.get("use_script")
    if use_script:
        get_text_from_pdf(config.doc_path)  # Here I am calling python function

    return render_template("engine.html")

还有蓝色按钮:

<a href="/engine?use_script=1" class="upload1"  style="padding: 0.8%; border-radius: 5px; width: 12%;"><i class="fa fa-upload"></i><span style="display:inline-block; width: 5px;"></span> Insight Engine</a>

其他选项可以在按钮中使用不同的路由,其中​​您 运行 脚本和 return redirect 到 /engine