Flask:向另一个路由传递参数

1 投票
1 回答
4199 浏览
提问于 2025-04-18 13:30

我正在制作一个应用程序,需要上传一个文件并对其进行处理。我可以成功上传文件,但在重定向时,无法将文件作为参数传递。这个文件是全局对象

@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 个回答

8

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

撰写回答