15
Flask: What’s In It For You by Douglas Starnes Learn how to: Write Python web apps quickly with Flask Use the free PyCharm Community Edition IDE Secure a Flask application with user accounts Retrieve and store data in databases Create a RESTful API And more!

What’s In It For You - samples.leanpub.comsamples.leanpub.com/flaskwhatsinitforyou-sample.pdf · Flask: What’s In It For You by Douglas Starnes Learn how to: • Write Python

Embed Size (px)

Citation preview

Page 1: What’s In It For You - samples.leanpub.comsamples.leanpub.com/flaskwhatsinitforyou-sample.pdf · Flask: What’s In It For You by Douglas Starnes Learn how to: • Write Python

Flask:What’s In It For Youby Douglas Starnes

Learn how to:• Write Python web apps quickly with Flask• Use the free PyCharm Community Edition IDE• Secure a Flask application with user accounts• Retrieve and store data in databases• Create a RESTful API• And more!

Page 2: What’s In It For You - samples.leanpub.comsamples.leanpub.com/flaskwhatsinitforyou-sample.pdf · Flask: What’s In It For You by Douglas Starnes Learn how to: • Write Python

Copyright 2016 Douglas A. StarnesAll Rights Reserved

Page 3: What’s In It For You - samples.leanpub.comsamples.leanpub.com/flaskwhatsinitforyou-sample.pdf · Flask: What’s In It For You by Douglas Starnes Learn how to: • Write Python

3

1GETTING STARTED

Welcome to Flask: What’s In It For You! Through this book we will examine the process of building and deploying a web application with Python and the Flask web micro-framework. This chapter will walk through installing the prerequisite software but before we do that, I want to take a minute to explain Flask and why it deserves serious con-sideration among web developers.

If you’ve spent any time in the Python world at all, you’ve likely heard of Django. Django is another web framework that predates Flask by a number of years. This might lead you to believe that because Django is older it is more mature, probably has more features, and better sup-port. And you might be wondering why would someone even consider another choice.

Django is what we might refer to as an opinionated web framework. What this means is that it is intended to work in a specific manner. I’ll give you an example. Web applications today are largely database-driv-en. Django took this into consideration and thus integrated an object relational mapper or ORM with the framework. An ORM allows a developer to work with data in a relational database using objects that represent the tables instead of writing SQL statements and parsing the results. And there is nothing wrong with this approach. At least until you want to use a database that is not supported by the Django ORM, such as MongoDB which is becoming very popular today.

Page 4: What’s In It For You - samples.leanpub.comsamples.leanpub.com/flaskwhatsinitforyou-sample.pdf · Flask: What’s In It For You by Douglas Starnes Learn how to: • Write Python

4

While it is possible to replace the Django ORM with something else, the process is not as easy as it could be. Flask however is easier. And this is a benefit of Flask being a micro-framework. A micro-framework stays out of your way, you could say it is unopinionated. It doesn’t expect your application to use a particular database. In fact, all Flask gives you by default is an HTTP stack plus some template processing function-ality. But even the templating is handled by an external framework. Other web app tasks such as login, caching, database access and APIs are delegated to extensions that you select and install during devel-opment. So Flask lets you make the choices that are the best for your application instead of forcing you to adapt to its preferences.

At this point the astute reader might be asking, if Flask is so flexible why use Django? Django still has its place in web apps! Django was created within the newspaper industry, so the original purpose was for content management. And it does this very well! So when you need to quickly stand up a forms-over-data style web application, Django is probably a better choice.

But the best way to prove the merits of Flask is to show you Flask devel-opment in action. And we’ll get to that in the next chapter. But for the rest of this chapter, I will walk you through the installation of the few prerequisites the rest of the book will require.

INSTALLING PYTHONAt the risk of overstating the obvious, Python is the ultimate require-ment for developing a Flask application. If you are using Linux, you likely have Python installed on your machine by default. The same goes for macOS (formerly Mac OS X). Windows users are not so lucky as Python is not distributed with Windows as of this writing. Howev-er, macOS and Linux user might need to install the specific version of Python that we will be using in this book.

Without going into details, I’ll explain that there are two versions of Python widely in use today, Python 2.x and Python 3.x. Development on Python 2.x has stopped although maintenance releases are still being

Page 5: What’s In It For You - samples.leanpub.comsamples.leanpub.com/flaskwhatsinitforyou-sample.pdf · Flask: What’s In It For You by Douglas Starnes Learn how to: • Write Python

5

deployed because Python 2.x is still widely used. But all new develop-ment is focused on Python 3.x which is 3.5.1 as of this writing. For this reason, I am going to use Python 3 in this book.

But first, Linux and macOS users can easily check to see if they have Python 3 installed. Open a terminal window and run the command:

$ python --version

If the version returned contains 3.4 or 3.5 (don’t worry about the minor version numbers) then you are good to go! If not, there is one more check that you can run:

$ python3 --version

If you still don’t see Python 3.4 or 3.5, don’t worry because there is still an easy way to get the version of Python we need on your system.

Installing Python has not always been that easy, especially on Windows. However, a company called Continuum Analytics in Austin, Texas has made it not only easy on Windows, not on easy on macOS and Linux, but they have made it work very consistently across platforms. The distribute a Python installer called Anaconda (to keep the snake theme alive) which accomplishes this. Even if you have the required version of Python installed on your machine, I recommend you install Anaconda.

To download Anaconda, go to https://www.continuum.io/downloads and look for the 3.x installer for your platform. The Windows installer is a Windows executable file. The Linux installer is a command line script that you run inside of the shell. For macOS you have two op-tions. First is a graphical installer which is a .pkg file. The second is a command line installer similar to the Linux installer. I recommend you use the graphical installer.

Page 6: What’s In It For You - samples.leanpub.comsamples.leanpub.com/flaskwhatsinitforyou-sample.pdf · Flask: What’s In It For You by Douglas Starnes Learn how to: • Write Python

6

NOTEYou may have read on the download page that you can down-load the installer for Python 2 and use it to install Python 3. While this is true to get started faster I recommend down-loading the Python 3 installer.

I’m not going to walk through the installation for each platform but I will add to read the directions carefully because the installer will ask you if you would like for Anaconda to be the default version of Python on your system. If you do not have the required version of Python or are not doing Python development right now, this is fine. But other-wise you might want to install Anaconda without making it the default version. And that’s OK too. Anaconda will live side-by-side with any existing Python installations.

PyCharm is distributed by a company called JetBrains. JetBrains has a long reputation with its Visual Studio add-on, Resharper. And their of-fering in the Python space is no slouch either. PyCharm comes in two flavor that will interest us. The first is PyCharm Professional Edition which is a paid commercial product. (You can get a 30-day trial) The second, which we will use in this book, is the free PyCharm Communi-ty Edition. Now even if you have the Professional Edition I recommend that you follow along with the Community Edition in this book. It’s free so you have nothing to lose! After working through this book I encourage you to download the 30-day trial of PyCharm Professional

INSTALLING PYCHARMThe other tool we need is a way to write to code and manage the re-sources of the application. There are many ways to do this, especially in the Python community. I know a lot of Python developers that still use vim. Others use a graphical but still minimalist editor like Atom. And while there is nothing wrong with either of those, I am going to use a graphical IDE in this book called PyCharm.

Page 7: What’s In It For You - samples.leanpub.comsamples.leanpub.com/flaskwhatsinitforyou-sample.pdf · Flask: What’s In It For You by Douglas Starnes Learn how to: • Write Python

7

Edition and consider purchasing it. PyCharm runs on Windows, ma-cOS and Linux.

To download PyCharm, go to https://www.jetbrains.com/pycharm/download/ (Figure 1-1). You’ll see links for each operating system and then a button for the Professional Edition trial and the Community Edition.

Figure 1-1 The PyCharm download page

The Windows installer is an executable file. It will then place links to PyCharm in your Start Menu. The macOS installer is a .dmg file with an application you drag into your Applications folder and launch. The Linux version is a .tar file that you must extract. Then from a ter-minal, cd into the bin/ directory and run the pycharm.sh script.

And that’s it! You’re ready to start developing Flask applications. In the next chapter, we’ll get our feet wet with PyCharm. We’ll also get the first taste of Flask by building a simple application.

Page 8: What’s In It For You - samples.leanpub.comsamples.leanpub.com/flaskwhatsinitforyou-sample.pdf · Flask: What’s In It For You by Douglas Starnes Learn how to: • Write Python

8

2YOUR FIRST FLASK

APPSo let’s create a Flask app! Start off by opening PyCharm Communi-ty Edition. You can use PyCharm Professional Edition if you have a license or the 30-day trial version but I am going to cover only features that are in the Community Edition. The screenshots in this book will be from the macOS version but there is not much difference from the Windows or Linux versions. I’ll try to point out the major differences as we go along. Upon opening PyCharm you should see the welcome dialog. (Figure 2-1)

Figure 2-1 The PyCharm welcome screen

Page 9: What’s In It For You - samples.leanpub.comsamples.leanpub.com/flaskwhatsinitforyou-sample.pdf · Flask: What’s In It For You by Douglas Starnes Learn how to: • Write Python

9

Click Create New Project to bring up the New Project dialog (Figure 2-2). Now if you are using PyCharm Professional Edition you will see many more options on the left side of the window, but the Community Edition only has one, Pure Python and that’s what I’ll be focusing on in this book.

First you’ll want to give your project a name and location. I’m going to leave the default location and change the name to demoapp. Next we need to select which version of Python to use. A recent 3.x version (3.4 and 3.5 are fine as of this writing) will work for us. The Interpreter dropdown will show all of the available Python versions on the ma-chine. It will also show any virtual environments. A virtual environ-ment is a sandboxed instance of a Python interpreter that is isolated from the rest of the system. This way you can have multiple versions of Python on the same machine and not worry about conflicts. Python best practice is to develop applications in a virtual environment and Py-Charm helps us to create them. Start by clicking the button to the right of the Interpreter dropdown (Figure 2-3).

Figure 2-2 Creating a new project

Figure 2-3 Adding a virtual environment

Note that there are two choices for creating a virtual environment. The first, Create VirtualEnv is what you use for a standard Python installa-tion such as the default installation on Linux or from python.org. The second choice, Create Conda Env, is if you have the Anaconda distribu-tion installed. The Anaconda distribution comes with a tool, conda, for managing virtual environments that is not compatible with virtualenv.

Page 10: What’s In It For You - samples.leanpub.comsamples.leanpub.com/flaskwhatsinitforyou-sample.pdf · Flask: What’s In It For You by Douglas Starnes Learn how to: • Write Python

10

I’m using Anaconda, so I’ll select the second one.

The next dialog (Figure 2-4) will ask for a name for the new environ-ment. The location will be updated to reflect this as well. Finally, you can select a Python version. If it is not installed already, conda will download it and install it into the environment. Note the dialog for creating an environment with virtualenv is similiar. The main differ-ence is the Python interpreter dropdown is limited to those installed on the machine.

Figure 2-4 Creating a new conda enivronment

PyCharm will prompt you for a file name. Enter app.py and create the new file. Next we need to add the Flask framework to our project. We can tell PyCharm to download and install Flask for us. PyCharm will also download and install any dependencies Flask requires. This is done in the project preferences. To get to the preferences in Windows

PyCharm will take a few seconds to create the new environment and copy over the files it needs. Then we are returned to the New Project dialog. Click Create to generate the new project.

The IDE will open up with an empty project. This project has no Py-thon files so we will start out by creating one. In the Project window on the left, right click the project folder, and then in the popup menu select New Python File. (Figure 2-5)

Figure 2-5 Creating a new Python file

Page 11: What’s In It For You - samples.leanpub.comsamples.leanpub.com/flaskwhatsinitforyou-sample.pdf · Flask: What’s In It For You by Douglas Starnes Learn how to: • Write Python

11

and Linux, select File Settings. In macOS, select Preferences from the PyCharm menu. Then on all platforms expand the Project item and select Project Interpreter. (Figure 2-6)

Figure 2-6 Project Preferences dialog

This will list all of the packages installed in the project. In our case these packages are installed in the virtual environment we created with the project. This is another advantage of virtual environments. Each one has a distinct set of packages that is isolated from the other virtual environments and the Python installations on the machine. For exam-ple, in just a minute we are going to install Flask version 0.11.1. Suppose later on that Flask 0.12.0 is released and you would like to try it out. If the set of packages installed was global to the machine, upgrading Flask could break some of your existing code. But if you create a new virtual enivronment and install the new version there, it won’t interfere with any existing virtual environments.

To install Flask, click the plus button beneath the package list. On Windows and Linux it is to the right of the package list. This will bring up a list of all the available packages PyCharm can install. In the search bar at the top, type ‘flask’. Select the ‘flask’ package in the list and then click the Install Package button. (Figure 2-7)

Close the Available Packages dialog. Note that Flask and several other packages have been added to the list. Click OK in the Preferences dia-log to close it as well. Back in the editor, add the following code to app.py:

Page 12: What’s In It For You - samples.leanpub.comsamples.leanpub.com/flaskwhatsinitforyou-sample.pdf · Flask: What’s In It For You by Douglas Starnes Learn how to: • Write Python

12

from flask import Flask

app = Flask(__name__)app.debug = True

@app.route(‘/’)def index(): return ‘Hello Flask!’

if __name__ == ‘__main__’: app.run()

123456789

101112

Listing 2-1 Our first Flask app

Figure 2-7 Installing the Flask package

We’ll go through the code in just a minute but first let’s get it running. Before PyCharm can start our app, it needs a run configuration. A run configuration tells PyCharm how to start our app, in this case it needs to know the path of the main Python file. In our app the choice is obvious because there is only one file. So we can generate a run config-uration by right clicking in app.py in the editor and then selecting Run ‘app’ in the popup menu. (Figure 2-8)

This will not only generate a run configuration, it will also start the application using that run configuration. The Run window will open at the bottom of the IDE. You should see some output similar to the following:

Page 13: What’s In It For You - samples.leanpub.comsamples.leanpub.com/flaskwhatsinitforyou-sample.pdf · Flask: What’s In It For You by Douglas Starnes Learn how to: • Write Python

13

* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) * Restarting with stat * Debugger is active! * Debugger pin code: 706-610-469

Figure 2-8 Running the app

Note that the first line says the application is running on the local address and port 5000. So that means we should be able to open a web browser to that address and port and see ‘Hello Flask!’ (Figure 2-9)

Figure 2-9 Hello Flask in the browser

Stop the application by clicking the red stop button to the left of the Run window. Let’s briefly look through the code.

Line 1 imports the class that will create a new Flask application. On line 3 it is used to create the application. The argument to the initializ-

Page 14: What’s In It For You - samples.leanpub.comsamples.leanpub.com/flaskwhatsinitforyou-sample.pdf · Flask: What’s In It For You by Douglas Starnes Learn how to: • Write Python

14

er is the name of the package where resources such as static files for this application can be found. For this simple app, the name of the current package will suffice. Line 4 sets the debug mode of the app. When the app is in debug mode it will listen for changes to source files and restart automatically. On line 7 we set up a route that maps a URL to a han-dler for all requests to that URL. We’ll discuss routes in more detail in the next chapter. For now know that a route decorates a function that is invoked when a request for the URL is received. The handler func-tion starts on line 8 and just returns a string on line 9. Flask will auto-matically wrap the string in an HTTP response. The application entry point is on line 11 and the app is run on line 12.

Don’t worry if that didn’t make complete sense yet. We’ll see a lot more Flask code in following chapters. For right now just know that the index function is invoked when a request to the root of the application is received. To prove this, we’ll set a breakpoint on line 9 and see Py-Charm’s excellent debugger at work. Click to the left of line 9 to set the breakpoint. (Figure 2-10)

Figure 2-10 Setting a breakpoint

Now when a request for the root on the application is received, Py-Charm will break and we can inspect the state of the applicaiton. But we have to tell PyCharm to debug the application as opposed to run-ning it. In the upper right of the IDE, there are two buttons. The first is a green arrow and that is the run button. The one next to it that looks like a green bug is the debug button. Click that button to start the application for debugging and then visit the root of the application in the browser again.

PyCharm paused execution at line 9 where we set the breakpoint. Now we can inspect any object in scope at that place in the app. The app object is shown in Figure 2-11. Note that the debug property is set to True like we set in the application. Again click the red stop button to stop the app:

Page 15: What’s In It For You - samples.leanpub.comsamples.leanpub.com/flaskwhatsinitforyou-sample.pdf · Flask: What’s In It For You by Douglas Starnes Learn how to: • Write Python

15

Figure 2-11 Inspecting the app at a breakpoint

Congratulations! You are now a Flask developer! Of course there is much more to Flask and PyCharm than we have seen in this chapter. In the next, we will look more in depth at how Flask gets URLs to handler functions and how we can use those URLs to pass data around. Stay tuned for more!