This is the first article in the series where I will document my experience of writing a web application in Python using the Flask microform.
Here is a list of all the articles in the series:
Part 1: Hello, World!
Part 2: Templates
Part 3: Forms
Part 4: Database
Part 5: User Login
Part 6: Profile Page and Avatars
Part 7: Unit Testing
Part 8: Subscribers, Contacts and Friends
Part 9: Pagination
Part 10: Full Text Search
Part 11: Email Support
Part 12: Reconstruction
Part 13: Date and Time
Part 14: I18n and L10n
Part 15: Ajax
Part 16: Debugging, Testing, and Profiling
Part 17: Deploying to Linux (even to Raspberry Pi!)
Part 18: Deploying to Heroku Cloud
My background
I’m a double-digit software developer with years of experience developing complex applications in multiple languages. I first met Python to create bindings to a C ++ library at work. In addition to Python, I wrote web applications in PHP, Ruby, Smalltalk and, believe it or not, in C ++. From all this, I find the Python / Flask combination the most flexible.
application
The application I am going to develop as part of this tutorial is a microblogging server, and I decided to call it
microblog . Pretty creative, I know.
')
During our progress, I will cover the following topics:
- User management, including management of logins, sessions, user roles, profiles, and user avatars
- Database management, including migration
- Form support, including field validation
- Pagination of long lists of items
- Full text search
- E-mail notifications to users
- HTML templates
- Multi-language support
- Caching and other performance optimization
- Debugging methods for development and production servers
- Installation on production server
As you can see, I take it all quite significantly. I hope that this application, when I finish it, will become something of a template for writing other web applications.
Requirements
If your computer supports Python 2.6 / 2.7, then everything will probably go well. The application from the manual should work fine on Windows, OS X and Linux.
This guide assumes that you are familiar with the terminal window (the command console in the case of Windows), and you know the basic commands for working with your OS files. If this is not the case, then before continuing, I recommend that you familiarize yourself with how to create directories, copy files, etc., using the console.
Finally, you should feel free to write Python code. Familiarity with the modules and packages of this language also does not hurt.
Flask installation
Well, let's get started!
If you have not yet installed Python 2.7, then take it
from here .
Now we need to install Flask and several extensions that we will use. I prefer to create a
virtual environment where everything will be installed in such a way that your basic Python installation will not be affected. As a bonus, you will not need root access to install in this way.
So, open the terminal, select the place where your application will be, and create a new folder in which it will be contained. Let's call this folder
microblog
.
Next, download
virtualenv.py and put it inside the new folder.
To create a new environment, enter the following command:
python virtualenv.py flask
This command will create a full Python environment inside the
flask
folder.
Virtual environments can be activated and deactivated as desired. An activated environment adds the path of its
bin
folder to the system path, for example, when you call the python interpreter, you get the version of the current environment, not the system one. Personally, I never liked this property, so I never activated any of my environments; instead, I simply called the interpreter I wanted, typing its way.
Note Lane: Before you start entering commands, I want to note that in the comments to the ninth part a bug in flask-whooshalchemy will be noted, the corrected version can be downloaded from here (author's repository)
If you are a Linux, OS x or Cygwin user, set the flask and extensions by entering the following commands one by one:
Command list flask / bin / pip install flask == 0.9
flask / bin / pip install flask-login
flask / bin / pip install flask-openid
flask / bin / pip install flask
flask / bin / pip install sqlalchemy == 0.7.9
flask / bin / pip install flask-sqlalchemy == 0.16
flask / bin / pip install sqlalchemy-migrate
flask / bin / pip install flask-whooshalchemy == 0.54a
flask / bin / pip install flask-wtf == 0.8.4
flask / bin / pip install pytz == 2013b
flask / bin / pip install flask-babel == 0.8
flask / bin / pip install flup
If you are a Windows user, the commands are slightly different:
Command list flask \ Scripts \ pip install flask == 0.9
flask \ Scripts \ pip install flask-login
flask \ Scripts \ pip install flask-openid
flask \ Scripts \ pip install sqlalchemy == 0.7.9
flask \ Scripts \ pip install flask-sqlalchemy == 0.16
flask \ Scripts \ pip install sqlalchemy-migrate
flask \ Scripts \ pip install flask-whooshalchemy == 0.54a
flask \ Scripts \ pip install flask-wtf == 0.8.4
flask \ Scripts \ pip install pytz == 2013b
flask \ Scripts \ pip install flask-babel == 0.8
flask \ Scripts \ pip install flup
These commands will download and install all the packages that we will use in our application.
Note that we are going to use Flask 0.9, not the latest version. Flask 0.10 was not quite long and some extensions are not ready to work with this version. There are also several incompatibilities between the packages and the latest version of
pip
, which are solved using specific versions for installation.
Windows users waiting for one more step. The observant reader will notice that there is no
flask-mail
in the list of commands for Windows. This extension is not installed purely on Windows, so we will work around it:
flask\Scripts\pip install --no-deps lamson chardet flask-mail
I will not go into details, so if you want to learn more, read the documentation for flask-mail.
If the installation of all the packages was successful, you can remove
virtualenv.py
, since we will no longer need the file.
"Hello, World!" In Flask
Now you have a
flask
subfolder in your
microblog
folder containing the Python interpreter and the Flask framework with extensions that we will use in this application. It's time to write our first web app!
After you have moved the
microblog
folder, let's create the basic folder structure for our application:
mkdir app mkdir app/static mkdir app/templates mkdir tmp
In the
app
folder we place our application itself. The
static
subfolder is needed to store statics, such as images, javascript files and style sheets. The
templates
subfolder is obviously intended for storing our templates.
Let's start by creating a simple initialization script for our
app
package (file
app/__init__.py
)
from flask import Flask app = Flask(__name__) from app import views
The script above simply creates an application object (inheriting
Flask
), then imports a view module that we haven’t written yet.
Views are handlers that respond to requests from a web browser. Representations in Flask are written as Python functions. Each view function is matched with one or more URL requests.
Let's write our first view function (
app/views.py
)
from app import app @app.route('/') @app.route('/index') def index(): return "Hello, World!"
This is a very simple view that simply returns a string for display in a custom browser. Two
route
decorators create a binding address
/
and
/index
to this function.
The final step to get a fully working web application is to create a script that starts the web server of our application. Let's call the
run.py
script and put it in the root directory (
microblog/
):
The script simply imports the
app
variable from our
app
package and calls the
run
method to start the server. Remember that the
app
variable is an instance of the
Flask
class, we created it above.
To run your application, simply run the script. On OS X, Linux and Cygwin, you should mark the file as executable before you can run it.
chmod a+x run.py
Then the script can be called simply:
./run.py
In Windows, the process is slightly different. No need to mark the file as executable. Instead, you need to run the script as a Python interpreter argument:
flask/Scripts/python run.py
After starting, the server will listen on port 5000, waiting for connections. Now open the browser and enter the following URL in the address bar:
Or you can use this link:
http://localhost:5000/index
Now did you see the routing in action? The first URL is bound to
/
, while the second is to
/index
. Both routes are associated with our view function, so they give the same result. If you enter any other route, you will get an error, since only these two were attached to the view function.
When you finish playing with the server you can just press Ctrl-C to stop it.
And with this I want to finish the first part of this guide.
Those of you who are too lazy to type can download the code from this guide below:
Download
microblog-0.1.zip .
Please note that you need to install Flask to run the application from the archive above.
What's next
In the next part of the series, we will change our little application to use HTML templates.
Hope to see you in the next part.
Miguel