Book Image

Flask Blueprints

By : Joel Perras
Book Image

Flask Blueprints

By: Joel Perras

Overview of this book

Table of Contents (14 chapters)

Preface

The setting is familiar enough: you're a web developer who has worked with a few programming languages, frameworks and environments, and decided to learn enough Python to make a few toy web applications. Maybe you've already used some Python web frameworks to build an application or two, and want to explore a few of the alternative options that you keep hearing about.

This is usually how people come to know about Flask.

As a microframework, Flask is built to help you and then get out of your way. Taking a very different approach from most other general-purpose web frameworks, Flask consists of a very small core that handles the processing and normalization of HTTP and the WSGI specification (via Werkzeug) and provides an exceptionally good templating language (via Jinja2). The beauty of Flask lies in its intrinsic extensibility: as it was designed from the start to do very little, it was also designed to be extended very easily. A pleasant consequence of this is that you are not beholden to a particular database abstraction layer, authentication protocol, or caching mechanism.

Learning a new framework is not simply about learning the basic functions and objects that are provided to you: it's often as important to learn how the framework can be adapted to help you build the specific requirements of your application.

This book will demonstrate how to develop a series of web application projects with the Python web microframework, and leverage extensions and external Python libraries/APIs to extend the development of a variety of larger and more complex web applications.

What this book covers

Chapter 1, Starting on the Right Foot – Using Virtualenv, kicks off our dive into Python web application development with the basics of using and managing virtual environments to isolate the application dependencies. We will look at the setup tools, pip, libraries, and utilities that are used to install and distribute reusable packages of Python code, and virtualenv, a tool to create isolated environments for the Python-based software requirements of a project. We will also discuss what these tools are not able to do, and look at the virtualenvwrapper abstraction to augment the functionality that virtualenv provides.

Chapter 2, Small to Big – Growing the Flask Application Structure, explores the various baseline layouts and configurations that you might consider for a Flask application. The pros and cons of each approach are outlined as we progress from the simplest one-file application structure to the more complex, multipackage Blueprint architecture.

Chapter 3, Snap – the Code Snippet Sharing Application, builds our first simple Flask application centered around learning the basics of one of the most popular relational database abstractions, SQLAlchemy, and several of the most popular Flask extensions: Flask-Login to handle authenticated user login sessions, Flask-Bcrypt to ensure that account passwords are stored in a secure manner, and Flask-WTF to create and process form-based input data.

Chapter 4, Socializer – the Testable Timeline, builds a very simple data model for a social web application where the main focus is on unit and functional testing using pytest, the Python testing framework and tools. We will also explore the use of the application factory pattern, which allows us to instantiate separate versions of our application for the purposes of simplifying testing. Additionally, the use and creation of often-omitted (and forgotten) signals, provided by the Blinker library, are described in detail.

Chapter 5, Shutterbug, the Photo Stream API, builds a skeleton of an application around a JSON-based API, which is a requirement for any modern web application these days. One of the many API-based Flask extensions, Flask-RESTful, is used to prototype the API, where we also delve into simple authentication mechanisms for stateless systems and even write a few tests along the way. A short detour is made into the world of Werkzeug, the WSGI toolkit that Flask is built upon, to build a custom WSGI middleware that allows the seamless handling of URI-based version numbers for our nascent API.

Chapter 6, Hublot – Flask CLI Tools, covers a topic that is often omitted from most web application framework discussions: command-line tools. The use of Flask-Script is explained, and several CLI-based tools are created to interact with the data models of our application. Additionally, we will build our very own custom Flask extension that wraps an existing Python library to fetch the repository and issue information from the GitHub API.

Chapter 7, Dinnerly – Recipe Sharing, introduces the somewhat intimidating concept of the OAuth authorization flow that many large web applications, such as Twitter, Facebook, and GitHub, implement in order to allow third-party applications to act on behalf of the account owners without compromising basic account security credentials. A barebones data model is constructed for a recipe-sharing application that allows the so-called social sign in and the ability to cross-post the data from our application to the feeds or streams of the services that a user has connected. Finally, we will introduce the concept of database migrations using Alembic, which allow you to synchronize your SQLAlchemy model metadata with the schemas of the underlying relational database tables in a reliable manner.

What you need for this book

To work through most of the examples in this book, all you need is your favorite text editor or IDE, access to the Internet (to install the various Flask extensions, not to mention Flask itself), a relational database (one of SQLite, MySQL, or PostgreSQL), a browser, and some familiarity with the command line. Care has been taken to indicate when additional packages or libraries are required to complete the examples in each chapter.

Who this book is for

This book was created for the new Python developers who wish to dive into the world of web application development, or for the seasoned Python web application professional who is interested in learning about Flask and the extension-based ecosystem behind it. To get the most out of each chapter, you should have a solid understanding of the Python programming language, a basic knowledge of relational database systems, and fluency with the command line.

Conventions

In this book, you will find a number of styles of text 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: "This will create a blank app1 environment and activate it. You should see an (app1) tag in your shell prompt."

A block of code is set as follows:

[default]
  <div>{{ form.password.label }}: {{ form.password }}</div>
  {% if form.password.errors %}
  <ul class="errors">{% for error in form.password.errors %}<li>{{ error }}</li>{% endfor %}</ul>
  {% endif %}

  <div><input type="submit" value="Sign up!"></div>
</form>

{% endblock %}

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 application.users.views import users
    app.register_blueprint(users, url_prefix='/users')

    from application.posts.views import posts
    app.register_blueprint(posts, url_prefix='/posts')

        # …

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

$ source ~/envs/testing/bin/activate
(testing)$ pip uninstall numpy

New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "Then it asserts that the Sign up! button text appears in the returned HTML".

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 may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to , and mention the book title via 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 on 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 for all Packt books you have purchased from your account at http://www.packtpub.com. 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 would 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 on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Piracy

Piracy of copyright 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

You can contact us at if you are having a problem with any aspect of the book, and we will do our best to address it.