Creating web forms
In Flask, we can choose from the following two approaches when implementing view functions for form data processing:
- Creating two separate routes, one for the
GEToperation and the other for thePOSTtransaction, as shown for the following user signup transaction:@app.route('/signup/form', methods= ['GET']) def signup_users_form(): resp = Response(response= render_template('add_signup.html'), status=200, content_type="text/html") return resp @app.route('/signup/submit', methods= ['POST']) def signup_users_submit(): username = request.form['username'] password = request.form['password'] user_type = request.form['utype'] firstname = request.form['firstname'] lastname = request.form['lastname'] cid = request.form['cid'] insert_signup(user=username, passw=password, utype=user_type, fname=firstname, lname=lastname, cid=cid) return render_template('add_signup_submit.html', message='Added new user!'), 200 - Utilizing only one view function for both the
GETandPOSTtransactions, as shown in the previoussignup_approve()route and in the followingassign_exam()view:@app.route('/exam/assign', methods=['GET', 'POST']) def assign_exam(): if request.method == 'GET': cids = list_cid() pids = list_pid() response = make_response(render_template('exam/assign_exam_form.html', pids=pids, cids=cids), 200) response.set_cookie('exam_token', str(uuid4())) return response, 200 else: id = int(request.form['id']) … … … … … … duration = int(request.form['duration']) result = insert_question_details(id=id, cid=cid, pid=pid, exam_date=exam_date, duration=duration) if result: exam_token = request.cookies.get('exam_token') return redirect(url_for('introduce_exam', message=str(exam_token))) else: return redirect('/error')
Compared to the first, the second approach needs request.method to separate GET from the POST transaction.
In setting up the form template, binding context data to the form components through render_template() is a fast way to provide the form with parameters with default values. The form model must derive the names of its attributes from the form parameters to establish a successful mapping, such as in the signup_approve() route. When it comes to retrieving the form data, the request proxy has a form dictionary object that can store form parameters and their data while its get_data() function can access the entire query string in byte stream type. After a successful POST transaction, the view function can use render_template() to load a success page or go back to the form page. It may also apply redirection to bring the client to another view.
But what happens to the form data after form submission? Usually, form parameter values are rendered as request attributes, stored as values of the session scope, or saved into a data store using a data persistency mechanism. Let’s explore how Flask can manage data from user requests using a relational database such as PostgreSQL.