46

I need get data from form.

I use JavaScript to create form:

<script> function checkAuth() { var user = ADAL.getCachedUser(); if (user) { var form = $('<form style="position: absolute; width: 0; height: 0; opacity: 0; display: none; visibility: hidden;" method="POST" action= "{{ url_for("general.microsoft") }}">'); form.append('<input type="hidden" name="token" value="' + ADAL.getCachedToken(ADAL.config.clientId) + '">'); form.append('<input type="hidden" name="json" value="' + encodeURIComponent(JSON.stringify(user)) + '">'); $("body").append(form); form.submit(); } } </script> 

then I need to get data from the input field which name="json".

Here is my view function:

@general.route("/microsoft/", methods=["GET", "POST"]) @csrf.exempt def microsoft(): form = cgi.FieldStorage() name = form['json'].value return name 

But I get an error:

builtins.KeyError KeyError: 'json'

Help me get data from form.

2
  • can you provide more detail please? Commented Feb 10, 2017 at 8:23
  • @WhatsThePoint script transmits data to the Python where they are processed. I need to pull value data from the name="json" Commented Feb 10, 2017 at 8:32

1 Answer 1

112

You can get form data from Flask's request object with the form attribute:

from flask import Flask, request app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def index(): data = request.form['input_name'] # pass the form field name as key ... 

You can also set a default value to avoid 400 errors with the get() method since the request.form attribute is a dict-like object:

from flask import Flask, request app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def index(): default_value = '0' data = request.form.get('input_name', default_value) ... 

P.S. You may also want to check out Flask-WTF for form validation and form HTML rendering.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks and how I can decode name? Because return answer eb2a-4390-8283-1be75d3ad422%22%2C%22oid%22%3A%22a3c6887f-614b-42b7-9a08-
That's a new question... You may need to accept my answer and write another question :)
How do you use this with the render_template?