loading

This instructable will guide you through setting up a Flask application. Flask is a web application framework for Python which allows for quick development, but is still very powerful. This allows you to build web applications quickly and powerfully. Flask isn't hard to setup, but it can be confusing and easy to overlook something the first time you do it. All in all, this should be able to be completed in less than three hours.

Step 1: Prerequisites

To make a fully running Flask application, it is MUCH easier to use a UNIX based operating system than other operating systems (like Windows). UNIX based operating systems include Mac OS X and Linux distributions. While it is possible to setup and run a Flask applications using Windows, it is much harder, and I will be using OS X in this tutorial.

To use this tutorial, you should:

  • Be familiar with the Python programming language
  • Have some experience with HTML and Javascript
  • Have some experience using commands in the terminal (command line)
  • Have an internet connection
  • Have pip installed. Pip is a package manager for python and can be installed here if you do not have it
  • Have a text editor of your choice, I recommend Atom

At the beginning of each step there is a picture of what your project structure should look like at the end of that step, which you can use as a reference.

Step 2: Base Setup

1. Create top-level project folder.
I will place this project in a directory called "workspaces", I would advise the use of a similar directory to hold other projects. My project will be called "instructables-flask-proj", you should choose an appropriate name and use that instead.
cd ~/workspaces
mkdir instructables-flask-proj
cd instructables-flask-proj
2. Create virtual environment
Virtual environments hold dependencies for your project, and are generally used to keep the requirements for different projects separate, so if you work on another project the requirements can't conflict. For this reason, I highly recommend using a virtual environment, though it isn't required.
pip install virtualenv
virtualenv venv
source venv/bin/activate
If you use a virtual environment, you will need to enter the third line every time you open a terminal window.

3. Install requirements
Now you can install the requirements for the project into your virtual environment.
touch requirements.txt
atom requirements.txt

You should enter the requirements into your "requirements.txt" file, one per line, which are:

Flask
Flask-Testing
nose

The first requirement is absolutely essential, while the last two are for testing. I highly recommend using a requirements file to allow other people who may work on the project to easily install requirements. After that, run

pip install -r requirements.txt

which will install these requirements.

Step 3: Setting Up the Controllers

1. Creating your first module

You will need to create your first module. Modules tend to contain all of the content for a single page, below I create a module below called "home", which we will be using for the home page of our sample application. From the root folder of your project:

mkdir home
cd home
touch __init__.py
touch views.py
atom views.py

The third line creates a file called "__init__.py" which may seem weird, but is required in all python modules. The "views.py" file will contain the controllers for the endpoints, or urls, for our home page.

2. Creating a controller

In your "views.py" file, you should enter something like:

from flask import Blueprint

home_view = Blueprint('home_view', __name__)

@home_view.route('/')  # Route for the page
def display_home_page():
	return 'Hello, World!'

There's two main parts to this, the blueprint and the display function.

The blueprint can be viewed as a collection of endpoints, usually grouped by page so you're application can be more modular. These will be much more valuable as your application grows.

The display function MUST have a decorator using the blueprint and the endpoint that this display function will service. In this case it is the root url for our web application. After that it is a simple Python function, later on we will look at how to return more complex views for the user.

Step 4: Running the Web Application

You may be wondering how we can run this web application now, which will be accomplished in this step.

1. Create the main file

Continuing from the previous step:

cd ..
touch settingslocal.py
atom settingslocal.py
touch instructables-flask-proj.py
atom instructables-flask-proj.py

You should not use the name "instructables-flask-proj.py", you should use the name of your own project. Note the "settingslocal.py" file. This is used for configuring parameters for the application setup, this isn't strictly needed now, but I would recommend setting it up now. The config file works by specifying python variables and their values, which act as key-value pairs, such as:

ATTR_ONE = '1'

Below is an example main file which you should be able to use in your application.

from Flask import flask
from home.views import home_view

def create_app(config_file):
	app = Flask(__name__)  # Create application object
	app.config.from_pyfile(config_file)  # Configure application with settings file, not strictly necessary
	app.register_blueprint(home_view)  # Register url's so application knows what to do
	return app

if __name__ == '__main__':
	app = create_app('settingslocal.py')  # Create application with our config file
	app.run()  # Run our application
<br>

2. Run the application

NOTE: Unlike the previous sections, you must use a terminal to run the application instead of it being recommended.

From the root of the application with the virtualenv active, run (using your own file name from the previous section):

python instructables-flask-proj.py

You should see some information printed in your terminal about where the application is running, it should default to http://127.0.0.1:5000/. Navigating to this link in a web browser should show the (extremely) basic webpage.

Step 5: Enhancing Your Webpage

1. Create the necessary directories and folders

mkdir templates
cd templates
touch home_page.html
atom home_page.html
cd ..
mkdir static
cd static
mkdir js
cd js
touch home_page.js
atom home_page.js
cd ../..

These will be the HTML and JavaScript files for our home page. These directories are the standard names in flask and I recommend you use them, however they can be specified to different names while creating the application in the previous step. You can now edit these files to display something you want, below is and example.

home_page.js:

alert('Testing JS');  // Simple alert to determine if file was imported

home_page.html:

<html>
<body>
	<h1>Our Home Page</h1>
	A list
	<ul>
		{% for i in range(num) %}
			<li>bullet {{i}}</li>
		{% endfor %}
	</ul>
</body>
<script type='text/javascript' src="{{url_for('static', filename='js/home_page.js')}}"></script>
</html>

You can see the result of this in the above picture. Note the use of the double curly braces and curly brace percent, these are used for templating. Flask uses a framework called "Jinja2" for this, which uses these symbols. Templating allows you to pass variables to the html page and control what is looks like before being sent to a browser. This is very powerful, and you can read more here

2. Change controller

The controller you made previously, in home/views.py, needs to be changed to return a display for this template, rather than a string. This is accomplished with the use of "render_template()" from flask, which you can think of as returning an html page. Below is what your home/views.py file should look like now.

<p>from flask import Blueprint, render_template</p><p>home_view = Blueprint('home_view', __name__)</p>@home_view.route('/')
def display_home_page():
	return render_template('home_page.html', num=10)

You should now be able to edit the parameter given to render_template() and the html file to control what is shown.

Step 6: Database

Up until now I haven't addressed the issue of databases, but at this point you should have a working web application you can plug a database into. Starting off easy, it's a good design principle not to access a database or perform computations in the views.py module. To accomplish this, you can use a file called api.py, then make calls to functions in this file from a display function in views.py.

cd home
touch api.py
atom api.py

This file can then be filled with functions that do calculations, get data from other services api through http calls, etc.

Flask is very flexible in the sense that many different types of databases can be used with the application you are building, and is often dependent on what your application will be doing. Some different choices are sqlite, mysql, and mongodb.

You should now have a working web application using Flask. As you saw, it wasn't incredibly difficult to setup. This tutorial barely scratched the surface of what Flask can do, and there are many libraries that work with Flask that can be a big help, such as Flask-Login and Flask-SQLAlchemy. Hopefully this helps you on your way to having a fully functioning web application!

<p>Cool!</p>

About This Instructable

1,237views

11favorites

License:

More by bshannan:Setting Up a Flask Application 
Add instructable to: