Issue
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.
Solution
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.
Answered By - Grey Li
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.