Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Mastering Flask Web and API Development

You're reading from   Mastering Flask Web and API Development Build and deploy production-ready Flask apps seamlessly across web, APIs, and mobile platforms

Arrow left icon
Product type Paperback
Published in Aug 2024
Publisher Packt
ISBN-13 9781837633227
Length 494 pages
Edition 1st Edition
Languages
Tools
Concepts
Arrow right icon
Author (1):
Arrow left icon
Sherwin John C. Tragura Sherwin John C. Tragura
Author Profile Icon Sherwin John C. Tragura
Sherwin John C. Tragura
Arrow right icon
View More author details
Toc

Table of Contents (18) Chapters Close

Preface 1. Part 1:Learning the Flask 3.x Framework
2. Chapter 1: A Deep Dive into the Flask Framework FREE CHAPTER 3. Chapter 2: Adding Advanced Core Features 4. Chapter 3: Creating REST Web Services 5. Chapter 4: Utilizing Flask Extensions 6. Part 2:Building Advanced Flask 3.x Applications
7. Chapter 5: Building Asynchronous Transactions 8. Chapter 6: Developing Computational and Scientific Applications 9. Chapter 7: Using Non-Relational Data Storage 10. Chapter 8: Building Workflows with Flask 11. Chapter 9: Securing Flask Applications 12. Part 3:Testing, Deploying, and Building Enterprise-Grade Applications
13. Chapter 10: Creating Test Cases for Flask 14. Chapter 11: Deploying Flask Applications 15. Chapter 12: Integrating Flask with Other Tools and Frameworks 16. Index 17. Other Books You May Enjoy

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 GET operation and the other for the POST transaction, 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 GET and POST transactions, as shown in the previous signup_approve() route and in the following assign_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.

You have been reading a chapter from
Mastering Flask Web and API Development
Published in: Aug 2024
Publisher: Packt
ISBN-13: 9781837633227
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime