Book Image

Mastering Flask

By : Jack Stouffer
Book Image

Mastering Flask

By: Jack Stouffer

Overview of this book

Starting from a simple Flask app, this book will walk through advanced topics while providing practical examples of the lessons learned. After building a simple Flask app, a proper app structure is demonstrated by transforming the app to use a Model-View-Controller (MVC) architecture. With a scalable structure in hand, the next chapters use Flask extensions to provide extra functionality to the app, including user login and registration, NoSQL querying, a REST API, an admin interface, and more. Next, you’ll discover how to use unit testing to take the guesswork away from making sure the code is performing as it should. The book closes with a discussion of the different platforms that are available to deploy a Flask app on, the pros and cons of each one, and how to deploy on each one.
Table of Contents (20 chapters)
Mastering Flask
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Preface

Flask is a web framework for Python that is specifically designed to provide the minimum amount of functionality that is needed to create web apps. Unlike other web frameworks, especially those in other languages, Flask does not have an entire ecosystem of libraries bundled with it for things such as database querying or form handling. Flask instead prefers to be an implementation agnostic.

The main feature of this setup is that it allows the programmer to design their app and their tools in any way they want. Not providing their own version of common abstractions also means that the standard library can be used much more often than other frameworks, which guarantees their stability and readability by other Python programmers. Because the Flask community is rather large, there are also many different community-provided ways of adding common functionality. One of the main focuses of this book is to introduce these extensions and find out how they can help avoid reinventing the wheel. The best part about these extensions is that if you don't need their extra functionality, you don't need to include them and your app will stay small.

The main downside of this setup is that the vast majority of new Flask users do not know how to properly structure large applications and end up creating an unintelligible and unmaintainable mess of code. This is why the other main focus of this book is how to create a Model View Controller (MVC) architecture with Flask apps.

Originally invented to design desktop user interfaces, the MVC setup allows the data handling (models), user interaction (controllers), and user interface (views) to be separated into three different components.

Separating these three different components allows the programmer to reuse code rather than re-implement the same functionality for each web page. For example, if the data handling code wasn't split into its own separate functions, we would have to write the same database connection code and SQL queries in each of the functions that render a web page.

A large amount of research and a lot of painful first-hand experience of what can go wrong while developing web applications has made this book the most comprehensive resource on Flask available, so I sincerely hope that you will enjoy reading it.

What this book covers

Chapter 1, Getting Started, helps readers set up a Flask environment for development using the best practices for Python projects. Readers are given a very basic skeleton Flask app that is built throughout the book.

Chapter 2, Creating Models with SQLAlchemy, shows how to use the Python database library SQLAlchemy in conjunction with Flask to create an object-oriented API for your database.

Chapter 3, Creating Views with Templates, shows how to use Flask's templating system, Jinja, to dynamically create HTML by leveraging your SQLAlchemy models.

Chapter 4, Creating Controllers with Blueprints, covers how to use Flask's blueprints feature in order to organize your view code while also avoiding repeating yourself.

Chapter 5, Advanced Application Structure, using the knowledge gained in the last four chapters, explains how to reorganize the code files in order to create a more maintainable and testable application structure.

Chapter 6, Securing Your App, explains how to use various Flask extensions in order to add a login system with permissions-based access to each view.

Chapter 7, Using NoSQL with Flask, shows what a NoSQL database is and how to integrate one into your application when it allows more powerful features.

Chapter 8, Building RESTful APIs, shows how to provide the data stored in the application's database to third parties in a secure and easy-to-use manner.

Chapter 9, Creating Asynchronous Tasks with Celery, explains how to move expensive or time-consuming programs to the background so the application does not slow down.

Chapter 10, Useful Flask Extensions, explains how to leverage popular Flask extensions in order to make your app faster, add more features, and make debugging easier.

Chapter 11, Building Your Own Extension, teaches you how Flask extensions work and how to create your own.

Chapter 12, Testing Flask Apps, explains how to add unit tests and user interface tests to your app for quality assurance and reducing the amount of buggy code.

Chapter 13, Deploying Flask Apps, explains how to take your completed app from development to being hosted on a live server.

What you need for this book

To get started with this book, all you will need is a text editor of your choice, a web browser, and Python installed on your machine.

Windows, Mac OS X, and Linux users should all be able to easily follow along with the content of this book.

Who this book is for

This book is written for web developers who are already somewhat familiar with Flask and want to take their Flask understanding from introductory to master level.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "The first() and all() methods return a value and therefore end the chain."

A block of code is set as follows:

class User(db.Model):
    id = db.Column(db.Integer(), primary_key=True)
    username = db.Column(db.String(255))
    password = db.Column(db.String(255))
    posts = db.relationship(
        'Post',
        backref='user',
        lazy='dynamic'
    )

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config.from_object(DevConfig)
db = SQLAlchemy(app)

Any command-line input or output is written as follows:

$ python manage.py db init

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Hit another button that says Download Bootstrap and you will start to download a Zip file."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail , and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at , and we will do our best to address the problem.