Reputation: 1619
I'm making a app in what I need upload a file and work with it. I can upload successfully, but when I redirect, I can't pass the file (like a argument). The file is 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')
This give this error:
AttributeError: '_RequestGlobals' object has no attribute 'get'
I'm doing wrong? Thanks!
Upvotes: 1
Views: 4297
Reputation: 160063
First, g
does not have a method called get
, so that won't work. You are looking for getattr
:
file = getattr(g, 'file', None)
Second, g
is created at the beginning of each request and torn down at the end of each request. Setting g.file
at the end of one request (right before it is torn down) will not make g.file
available at the beginning of another.
The right way to do this is either to:
Store the file on the file-system (using a uuid for a name, for example) and pass the file's uuid to the other endpoint:
@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
Move the code from experiment
into analyze
Upvotes: 8