GreatWhite GreatWhite - 5 months ago 35
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 view.py

@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))
else:
return render_template('login.html')


@app.route("/test/", methods=['POST'])
def test():
name = request.form['login']
password = request.form['password']
input = ['/mypath/test.py', name, password]
a = subprocess.Popen(input, stdout = subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=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">
</form>


Traceback:

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

Answer

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