Python 如何从函数外部使用flask变量,以便以后在javascript中使用?

Python 如何从函数外部使用flask变量,以便以后在javascript中使用?,python,flask,Python,Flask,Running routes.py @app.route('/articles', methods=['GET', 'POST']) def articles(): upload() return render_template('articles.html') 这个功能保存图像并处理其信息 def upload(): if request.method == 'POST': # Save the file to static/uploads

Running routes.py

@app.route('/articles', methods=['GET', 'POST'])
def articles():
    upload()
    return render_template('articles.html')
这个功能保存图像并处理其信息

def upload():
    if request.method == 'POST':
        # Save the file to static/uploads
    
        label = "some string from process above"
        probability = "another string"

        return None

    return None
如何在呈现模板时使用变量标签和概率?有些人使用的东西接近:

return render_template('articles.html', label=label, probability=probability)

这样做是为了使用js引用变量。但是,如果该变量是在upload()中计算的,那么如何引用该变量呢?是否需要全局变量?

您可以从函数返回这些变量


您必须解压缩从
upload
函数发送的变量

首先,您必须从
upload
返回它们,然后将其解压缩以发送到
render\u template

@app.route('/articles', methods=['GET', 'POST'])
def articles():
    label, probability = upload()
    return render_template('articles.html', label=label, probability=probability)

您可以从函数中返回这些变量。如果我像返回标签一样返回它们,我将能够在其他地方直接使用它们,或者我应该定义标签,probability=upload()?您必须解压缩从函数发送的变量,因此首先,您必须从
上传
返回它们,然后将其解包发送到
呈现模板
。谢谢,现在每个html/javascript id都将是呈现模板()中指定的名称,对吗?我不确定这里的
id
是什么?例如,它将易于使用并显示标签中的文本?是,您当然可以通过使用类似以下内容来实现这一点{{label}}
def upload():
    if request.method == 'POST':
        # Save the file to static/uploads
    
        label = "some string from process above"
        probability = "another string"

        return (label, probability)

    return (None, None)