Skip to main content
 首页 » 编程设计

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

2025年05月04日13leader

我正在制作一个应用程序,我需要上传一个文件并使用它。我可以成功上传,但是当我重定向时,我无法传递文件(如参数)。文件是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' 

我做错了吗? 谢谢!

请您参考如下方法:

首先,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