My new blog here at www.mostovenko.com

Thursday, April 12, 2012

Flask - lightweight and awesome. Get started - creating antigravity-app (part1)

Part 1. Intro,configuration of  development environment, creating backbone for flask app.

Why flask?
Actually i don't want to propagate and ensure you that flask is a good choice for building web app. Let's say - you need to try it by your self at first, and after that, you will do all conclusions.

Haven't hear anything about flask?
One of a big advantages of this framework is it's mailing list, community and good documentation. So i suggest you to find some basic information on this page and only after that return to this article.
All tutorial sources is available on bitbucket

Why do we need a strange app with a weird name "antigravity-app"?
I am going to cover a number of aspects of building flask apps in this blog. So, to prevent repeatition of creation new test app for each separate article i suggest you to follow this tutorial and create basic modular app. Lets call it antigravity-app. Every new feature that i will  be explaining later - will be just new module for our antigravity-app. 


So, in this part of  tutorial i will cover:
  1.  Creation of basic structure for building flask apps.
  2. settings.py module.
  3. app.py application factory.
  4. manage.py module for our app(manage.py like in django)
Ok, so let's get started?
If you are ready to start, lets check some necessary steps, that you already must have been done  after reading this quickstart.
  •  Virtualenv installation. This is very comfortable tool, so if you haven't yet installed - shame on you,  go ahead and install it. Good description is here
    • In our app we will be using python2.7 so when creating virtual environment set python version to 2.7. To reproduce this just add  "--python=python2.7" parameter while creating virtualenv.
      bash:
      virtualenv --python=python2.7 antigravity-app
  • Activate virtualenv(. antigravity-app/bin/activate)
  • Install Flask (pip install Flask)
  • Create working folder for our project somewhere in your hard disk, name it "antigravity-app".
And that's it! We are ready to create backbone of our app.
Creating app backbone.
When i only started learning flask, i have met a lot of "get-started tutorials" that shown me how  to launch application with minimum effort. And if you will look at simple hello world application for Flask, you will understand that it's quite easy to do this. But in this tutorial i will try to show how to build more scalable architecture for flask applications. I love DRY, lose coupling, modularity, so i will suggest my vision of flask app architecture to you. I don't want to say that this is the only one right - i am just proposing and you may agree or not. 

Ok, i think a lot of words for now, let's do some useful staff!!!!

App structure:
initial app files structure










Some comments to initial structure:
packages:
  • antigravity_core  - package for holding logic that can be reused by different modules in antigravity app. 
  • antigravity_modules - package for holding  separate app modules.
folders:
  • static - folder for keeping our css, html, javascript.
  • templates - folder for keeping templates for our app.
modules:
  • app-factory.py - module for providing factory method for creating application instance.
  • manage.py - module for managing our application.
  • settings.py - module for keeping our application settings.
If you think that something is missing in this initial structure - you are absolutely right. I will be adding all missing parts in future articles, to provide more deep understanding of for what we need those missing blocks.

settings.py
First we will fill some info about or app in settings module.

import os
#Generic app settings.
APP_HOST = "127.0.0.1"
APP_PORT = "5001"
DEBUG = True
TEMPLATE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')
STATIC_PATH = '/static'

I gues everything is clear from settings. Here we are setting generic app settings, such as application host, port, debug mode, path to template dirrectory and static path. As we see template dirrectory path is defined dynamically, so we don't need to change it on each time -when we want to change projects place on a hard-disk.

app_factory.py
Second module will be application factory. You may ask me - do we really need factory for app? I will answer  - ofcourse!!! It gives us more flexible architecture Just for instance, later we will provide unit-tests for our app, and application factory will give us ability to create our app instance with test-settings.
Let's look at the code of settings.py module:
from flask import Flask

#----------------------------------------------------------------------
def create_app(config_file):
    """
    Creating app object.
    Parameters:
    @config_file : python module with application settings.
    """

    app = Flask(__name__)
    app.config.from_object(config_file)
    return app

Ofcourse,  later we will update this method  with another useful features as: registering modules(Blueprints), adding some login and database request handlers, but it's all will be a little bit later. Here i want to underline, that we may set app settings in couple of ways, but i found it very comfortable to set them from python module(settings.py)

manage.py
I think that it is not bad idea - to create separate module for providing manage logic for our app. From my point of view, managing logic, at least, must include : launching app, launching tests and synchronizing our models with database. Flask has very useful package for implementing this feature. It's called Flask-script. It's quite good documented tool, so i propose to read this doc for getting more information about this package.
To install it just type in your terminal window this command  "pip install Flask-script" and you will be ready to use it(remember that our virtual environment for antigravity-app must be activated). To get the world round and try to launch our app we need to add the following lines to manage.py module:
from flaskext.script import Manager, Server
from app_factory import create_app
import settings

manager=Manager(create_app(settings))

#Initializing server instance.
server = Server(host=settings.APP_HOST, port=settings.APP_PORT)

#Adding command for runing the server.
manager.add_command("runserver", server)

if __name__ == "__main__":
    manager.run()
Here we are defining "runserver" command, to provide launching of our app. I know that for now it is not as flexible as it could be, but for know, for better understanding, i decided to left it like it is. Later, when we will need more flexability in this module - we will upgrage it. That's it, we may test how  our app is running by typing in terminal "python manage.py runserver". If everything was done right - you will see such information in output:
  * Running on http://127.0.0.1:5001/
  * Restarting with reloader
Great i may congratulate you with finishing the first part of my flask tutorial. Thanks for attention.
At the next section we will add some static for UI, create simple view and template in our first module for antigravity-app.

P.S. If you will find some errors - please let me know))) Good luck.
Next article