Flask:将参数传递给另一条路线

时间:2014-07-16 05:26:18

标签: python redirect flask

我正在制作一个应用程序,我需要上传文件并使用它。我可以成功上传,但是当我重定向时,我无法传递文件(就像参数一样)。该文件为global objects

@app.route('/analysis', methods = ['GET', 'POST'])
def analysis():
    if request.method == 'POST':
        file = getattr(g, 'file', None)
        file = g.file = request.files['file']
        return redirect(url_for('experiment'))
    else:
        return render_template('upload.html')

@app.route('/experiment', methods = ['GET', 'POST'])
def experiment():
    file = g.get('file', None)
    filename = secure_filename(file.filename)
    if request.method == 'POST':
        #do something with the file
        return render_template('experiment.html', data = data)
    else:
        return render_template('experiment.html')

这会出现此错误:

AttributeError: '_RequestGlobals' object has no attribute 'get'

我做错了? 谢谢!

1 个答案:

答案 0 :(得分:6)

首先,g没有名为get的方法,因此无效。您正在寻找getattr

file = getattr(g, 'file', None)

其次,g在每个请求开始时创建,并在每个请求结束时拆除。在一个请求结束时设置g.file(在它被拆除之前)将不会在另一个请求的开头提供g.file

正确的方法是:

  • 将文件存储在文件系统上(例如,使用uuid作为名称)并将文件的uuid传递给另一个端点:

    @app.route("/analyze", methods=["GET", "POST"])
    def analyze():
        if request.method == "POST":
            f = request.files['file']
            uuid = generate_unique_id()
            f.save("some/file/path/{}".format(uuid))
            return redirect(url_for("experiment", uuid=uuid))
    
    @app.route("/experiment/<uuid>")
    def experiment(uuid):
        with open("some/file/path/{}".format(uuid), "r") as f:
            # Do something with file here
    
  • 将代码从experiment移至analyze