Book Image

Flask By Example

By : Gareth Dwyer
Book Image

Flask By Example

By: Gareth Dwyer

Overview of this book

This book will take you on a journey from learning about web development using Flask to building fully functional web applications. In the first major project, we develop a dynamic Headlines application that displays the latest news headlines along with up-to-date currency and weather information. In project two, we build a Crime Map application that is backed by a MySQL database, allowing users to submit information on and the location of crimes in order to plot danger zones and other crime trends within an area. In the final project, we combine Flask with more modern technologies, such as Twitter's Bootstrap and the NoSQL database MongoDB, to create a Waiter Caller application that allows restaurant patrons to easily call a waiter to their table. This pragmatic tutorial will keep you engaged as you learn the crux of Flask by working on challenging real-world applications.
Table of Contents (20 chapters)
Flask By Example
Credits
About the Author
Acknowledgements
About the Reviewers
www.PacktPub.com
Preface
Index

Expanding your Flask knowledge


You might expect that Flask, being a micro framework, could be covered in its entirety in a single book. However, there are some potentially very useful parts of Flask that we didn't need for any of our three projects. We'll briefly outline these here.

VirtualEnv

The first library worth mentioning is not actually Flask-specific, and if you've spent some time on Python development before, you will almost certainly come across it. VirtualEnv is a Python library that creates a virtual Python environment on your machine. It can be used in conjunction with Flask either only on your development machine or both on your development machine and server. Its main purpose is to isolate your entire Python environment into a virtual one, including all the Python modules that you use. This has two major benefits. The first is that sometimes you need to run two different Python projects on the same machine, but each project requires a different version of the same library. Using VirtualEnv, each project would have its own virtualized version of the Python setup, so it becomes trivial to install two different version of the same library. The second advantage is that your environment becomes more portable, and in theory, it is easy to migrate an application running in a VirtualEnv environment to another machine that has VirtualEnv installed.

The VirtualEnv environment is widely used for Python development, especially for Flask. My decision to not include it in the main body of the book proved highly controversial with the reviewers, many of whom felt that the book was incomplete without it. I decided not to include it for two reasons. The first is that while I was learning Flask, I read many tutorials and examples, which included VirtualEnv. I always found the extra work needed for the setup and explanation of VirtualEnv and virtual environments in general to be distracting from the main content of the tutorial (namely, using Flask). The second reason is that I still often do not use it in the Flask projects I build today. If you're not running old software that depends on a particular version of a particular library, then installing useful Python libraries system-wide so that they can be used by all your Python applications is convenient. Also, sometimes, VirtualEnv can just become a mission without providing any value.

Of course, you may already have your own opinion on VirtualEnv, in which case you're welcome to go along with it. There's nothing stopping anyone from building any of the projects in this book in a VirtualEnv environment if they have a little experience. If you have not used it before, it's well worth looking at. You can install it through pip and try it out to take a look at exactly what it does and whether it can be of use in your particular scenario. You can read more about it and how to use it here:

http://docs.python-guide.org/en/latest/dev/virtualenvs/

Flask Blueprints

Perhaps the biggest feature of Flask that we haven't mentioned in this book is Flask Blueprints. You must have noted after building three Flask applications that certain patterns crop up time and again. Repeated code is bad code even over a number of different applications; if you find a better way to do something or need to make some changes for an update, you don't want to make the same change across several applications.

Blueprints provide a way to specify patterns for a Flask application. If you have several applications that use the same code to return templates or connect to a database, you can rather write this common code in a blueprint and then have all the applications register the blueprint.

You can read more about Flask Blueprints, take a look at examples, and learn how to get started with using them at http://flask.pocoo.org/docs/0.10/blueprints/.

Flask extensions

We looked at quite a few different Flask extensions over the course of our three projects. However, because of the educational focus of the book, we chose to write some code from scratch that may be better off using existing extensions. (Generally when developing, we want to avoid reinventing the wheel. If someone else has already put thought into solving a problem and provided a well-developed and well-maintained solution, it's better to use their offerings than to try and create our own.) Of special interest are the extensions we could use to make our user account system simpler and more powerful and those that offer us a more abstract way to talk to our database.

Flask-SQLAlchemy

Another controversial decision in this book was of not introducing the Flask-SQLAlchemy extension along with MySQL. SQLAlchemy provides a SQL toolkit and ORM to make it easier and more secure to interact with SQL databases from a Python environment. ORM provides another layer of abstraction between the web application and database. Instead of having to write the SQL code directly, one can make calls to a database using Python objects, which ORM will then translate to and from SQL. This makes the database easier to write and maintain and also more secure (ORM is normally very good at mitigating against any potential SQL injection vulnerabilities). The reasons to omit it were similar to the reasons to omit VirtualEnv—when learning, too many layers of abstraction can do more harm than good, and it's always advantageous to have first-hand experience with the problems that tools solve before blindly using the tools directly.

For any Flask application that uses a MySQL database, such as our Crime Map project, it is highly recommendable to use ORM, as with most Flask extensions. Flask-SQLAlchemy is just a wrapper for an existing non-Flask-specific library. You can find out more about SQLAlchemy at http://www.sqlalchemy.org/ and a comprehensive guide to Flask-SQLAlchemy, including common usage patterns, here:

http://flask.pocoo.org/docs/0.10/patterns/sqlalchemy/

Flask MongoDB extensions

There are several Flask extensions that are intended to make interfacing with MongoDB easier. As MongoDB is relatively new, none of these has reached quite the maturity or is in as wide use as SQLAlchemy; therefore, if you intend to use one of them, it is recommended that you examine each to decide which one best suits your needs.

Flask-MongoAlchemy

Perhaps the most similar to SQLAlchemy (and not just by name) is Flask-MongoAlchemy. Similarly to SQLAlchemy, MongoAlchemy is not Flask-specific. You can read more about the main project here at http://www.mongoalchemy.org. Flask-MongoAlchemy is a Flask wrapper for MongoAlchemy, which you can read more about here:

http://pythonhosted.org/Flask-MongoAlchemy

Flask-PyMongo

A thinner wrapper to MongoDB that is closer to using PyMongo directly as we did in our third project is Flask-PyMongo. Unlike MongoAlchemy, this does not provide an ORM equivalent; instead, it simply provides a way of connecting to MongoDB through PyMongo using syntax that is more consistent with the way Flask usually handles external resources. You can have a quick introduction to Flask-PyMongo on its GitHub page here:

https://github.com/dcrosta/flask-pymongo

Flask-MongoEngine

Yet another solution to using Flask in conjunction with MongoDB is MongoEngine (http://mongoengine.org). This is notable because it integrates with WTForms and Flask-Security, which we'll discuss in the following sections. You can read more about the Flask-specific extension for Mongo Engine at https://pypi.python.org/pypi/flask-mongoengine.

Flask-Mail

If we wanted to implement an automatic e-mail sending solution, such as that described earlier in this chapter, a helpful extension would be Flask-Mail. This allows you to easily send e-mails from your Flask application along with handling attachments and bulk mailing. As mentioned before, these days, it's worthwhile to consider using a third-party service such as Amazon's SES instead of sending e-mails yourself. You can read more about Flask-Mail at http://pythonhosted.org/Flask-Mail.

Flask-Security

The final extension we'll talk about is Flask-Security. This extension is notable because a large part of it is actually built by combining other Flask extensions. In some ways, it departs from the Flask philosophy of doing as little as possible to be useful and allowing the user full freedom for custom implementations. It assumes that you are using one of the database frameworks we described, and it pulls together functionality from Flask-Login, WTForms, Flask-Mail, and other extensions to attempt to make building user account control systems as straightforward as possible. If we used this, we would have had a centralized way of handling registering accounts, logging in accounts, encrypting passwords, and sending e-mails instead of having to implement each part of the login system separately. You can read more about Flask-Security here:

https://pythonhosted.org/Flask-Security

Other Flask extensions

There are many Flask extensions, and we've only highlighted the ones that we think would be generally applicable in many web development scenarios here. Of course, when you develop a unique web application, you'll have much more specific needs, and chances are that someone has already had a similar need and created a solution. You can find an extensive (but not complete) list of Flask extensions here:

http://flask.pocoo.org/extensions