GreatWhite GreatWhite - 1 year ago 93
Python Question

Pass post data to a script flask

I have a page that needs to take two arguments which I want to send in a POST request, Login and Password. I keep getting an IndexError: list index out of range from flask, I'm assuming because it is not receiving the arguments for the script.

This is my

@app.route("/login/", methods=['GET','POST'])
def login():
if request.method == 'POST':
name = request.form['login']
password = request.form['password']
return redirect(url_for('test', name=name, password=password))
return render_template('login.html')

@app.route("/test/", methods=['POST'])
def test():
name = request.form['login']
password = request.form['password']
input = ['/mypath/', name, password]
a = subprocess.Popen(input, stdout = subprocess.PIPE,
out = a.communicate()
return out

and form

<form action="{{ url_for('test') }}" method="POST">
<input type="text" name="login">
<input type="password" name="password">
<input type="submit" value="Go">


Traceback (most recent call last)
File "/usr/lib64/python3.4/site-packages/flask/", line 2000, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/lib64/python3.4/site-packages/flask/", line 1991, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/usr/lib64/python3.4/site-packages/flask/", line 1567, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/lib64/python3.4/site-packages/flask/", line 33, in reraise
raise value
File "/usr/lib64/python3.4/site-packages/flask/", line 1988, in wsgi_app
response = self.full_dispatch_request()
File "/usr/lib64/python3.4/site-packages/flask/", line 1642, in full_dispatch_request
response = self.make_response(rv)
File "/usr/lib64/python3.4/site-packages/flask/", line 1743, in make_response
File "/usr/lib/python3.4/site-packages/werkzeug/", line 778, in __init__
self.status = status
File "/usr/lib/python3.4/site-packages/werkzeug/", line 886, in _set_status
self._status_code = int(self._status.split(None, 1)[0])
IndexError: list index out of range

Answer Source

Your script is receiving the POST values just fine; it is returning the response from your view that is the issue here. You are not returning something that Flask expects to be returned.

You are returning a tuple of strings here:

out = a.communicate()
return out

because the Popen.communicate() method returns a tuple of (stdout, stderr).

When you return a tuple with two string elements, Flask expects that to be a response body and a status code. Since your stderr string is empty, parsing of the status code (which could be in the form of a '200 Ok' or '404 Not Found', etc. form) fails.

Return just the stdout result:

stdout, stderr = a.communicate()
return stdout
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download