Python 如何在href标记中使用flask变量?

Python 如何在href标记中使用flask变量?,python,flask,Python,Flask,下面是使用flask和python上传文件的代码,然后我希望使用href标记中的filename变量 我正在尝试使用{{filename},但无法访问它 def index(): if request.method == 'POST': file = request.files['file'] if file and allowed_file(file.filename): filename = secure_filenam

下面是使用flask和python上传文件的代码,然后我希望使用href标记中的
filename
变量

我正在尝试使用
{{filename}
,但无法访问它

    def index():
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            path = "./audiofile.txt"
            filepath = open(path, "w")
            filepath.write(filename)           
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            filepath.close()
            os.system('python ../speech-to-text/slow.py')
            os.system('python ../sentiment-analysis/test.py')
            return redirect(url_for('index'))
    return """
    <!doctype html>
    <head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>Online audio/video transcription!</title>

  <link rel="stylesheet" type="text/css" href="static/bootstrap.min.css"/>
  </head>
    <title>Upload new File</title><br>
    <center>
    <h1>Upload new File</h1><br>
    <form action="" method=post enctype=multipart/form-data>
      <p><input type=file name=file><br/><br/>
         <input class=btn-success type=submit value=Upload>
    </form>
    <hr>
    <h4>Download transcript file (with sentiment analysis) <a href="tmp/{{filename}}.txt">here</a>!</h4>
    </center>

    <p>%s</p>
    """ % "<br>"
def index():
如果request.method==“POST”:
file=request.files['file']
如果文件和允许的文件(file.filename):
filename=secure\u文件名(file.filename)
path=“./audiofile.txt”
filepath=open(路径“w”)
filepath.write(文件名)
保存(os.path.join(app.config['UPLOAD\u FOLDER'],文件名))
filepath.close()
system('python../speech-to-text/slow.py')
系统('python../touction analysis/test.py')
返回重定向(url_for('index'))
返回“”
在线音频/视频转录!
上载新文件
上载新文件



下载成绩单文件(带情绪分析)! %

“%”

这个问题有点含糊不清,但我会尽量回答你的问题

为了使用Jinja2 synthax在HTML中使用filename变量,首先必须将该文件名传递到HTML中

因此,您的简化视图函数如下所示

@app.route('/upload_something/', methods=['GET', 'POST'])
def upload_something():

   # a line to produce filename variable or to get it back from HTML is needed here

   if request.method == 'POST':
       # your upload starts here.


   return render_template('file_upload.html', file_name = file_name)

一旦将文件名传递到HTML中,就可以开始使用Jinja2 synthax{{{file_name}}

在if语句之外返回上面的HTML部分。变量'filename'是在if语句中创建的,在该语句的末尾有一个重定向到url_for('index')(我不知道index的模板是什么样子),因此它甚至不会到达您粘贴在这里的HTML代码。