Python Flask:将参数传递到另一个路由

Python Flask:将参数传递到另一个路由,python,redirect,flask,Python,Redirect,Flask,我正在制作一个应用程序,我需要上传一个文件并使用它。我可以成功上传,但当我重定向时,我无法传递文件(如参数)。这个文件是 这将导致以下错误: AttributeError: '_RequestGlobals' object has no attribute 'get' 我做错了? 谢谢 首先,g没有名为get的方法,因此这不起作用。您正在查找getattr: file = getattr(g, 'file', None) 其次,g在每个请求开始时创建,并在每个请求结束时分解。在一个请求结束时

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

这将导致以下错误:

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
    
    @app.route(“/analyze”,方法=[“GET”,“POST”])
    def analyze():
    如果request.method==“POST”:
    f=请求.files['file']
    uuid=生成唯一的id()
    f、 保存(“some/file/path/{}”.format(uuid))
    返回重定向(url_代表(“实验”,uuid=uuid))
    @应用程序路径(“/experiment/”)
    def试验(uuid):
    将open(“some/file/path/{}”.format(uuid),“r”)作为f:
    #在这里处理文件
    
  • 将代码从
    实验
    移动到
    分析


首先,
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
    
    @app.route(“/analyze”,方法=[“GET”,“POST”])
    def analyze():
    如果request.method==“POST”:
    f=请求.files['file']
    uuid=生成唯一的id()
    f、 保存(“some/file/path/{}”.format(uuid))
    返回重定向(url_代表(“实验”,uuid=uuid))
    @应用程序路径(“/experiment/”)
    def试验(uuid):
    将open(“some/file/path/{}”.format(uuid),“r”)作为f:
    #在这里处理文件
    
  • 将代码从
    实验
    移动到
    分析