Introduction To Flask

Flask is a micro python framework which handle all the basic stuff needed to build a powerful web application. Its lightweight and flexible framework.You can build web application easily and in short time.

Flask provides features such as routing, secure cookies, tempting engine etc. So in this tutorial we will setup a Flask on server and run a rendered html page.

First of all you need to install few things in order to go ahead in this tutorial

We will install Virtualenv. Its like virtual environment which allows multiple python installation for your project.

Mac

Install virtualenv using command

sudo easy_install virtualenv  
or  
sudo pip install virtualenv  

Ubuntu/Debian

For ubuntu or debian operating system, use the folowing command

sudo apt-get install python-virtualenv

Windows

On windows i won’t prefer using Flask .If you are on Windows and don’t have the easy_install command, you must install it first. But if you would like to you can use this url

http://flask.pocoo.org/docs/installation/#windows-easy-install

Getting started with Virtualenv

Virtualenv is installed. Now its time to use it.
Create a directory using mkdir command on Desktop or wherever you want to.

mkdir flask

After that you need to activate virtual environment and setup for your folder. Now outside flask directory use this command

virtualenv flask source flask/bin/activate

It will setup python and libraries in flask folder.You are now ready to go with that.

Note: Use this virtualenv command outside of folder in which you want to setup.

Installing Flask

On ubuntu and mac ,Change directory to flask by

cd flask

Type this command:

pip install flask

Now flask is installed and you can use it as python module.

Create A Flask Application

Create file index.py in flask directory. On mac and linux you can use touch command

touch index.py

Edit that file using your favourite text editor

Put this code and run that as python file

from flask import Flask  
app = Flask(__name__)

@app.route("/")
def index():  
    return "Hello World!"

if __name__ == "__main__":  
    app.run()

Now save it and run using

python index.py

And open http://127.0.0.1:5000
And you will see Hello World! output in browser

Explanation of Code.

  • We are first importing flask class and using it in current file.

  • Creating instance of flask class in second line.

  • Defined route (“/”) using app decorator so that we can use url to call different function.Here single slash define the index page.

  • Created index function and using it to call Hello World

  • Using run method to run local server and Flask App.

You can stop the server by Control-C.


Flask application detailed version

File structure goes like this

flask ->  
    index.py
    templates ->
           index.html
           login.html
           register.html
    static  ->
          bootstrap.css

Templates folder is used to store html file that is either static or to be rendered by flask and static folder is used to store css,js,img files

Create a structure like this and Code for index.py goes like this

from flask import Flask , render_template, request

app = Flask(__name__)

#homepage get method
@app.route("/")
def index():  
    return render_template('index.html')

#get method login page
@app.route('/login')
def login():  
     return render_template('login.html',title='Login Page')

#post method login page
@app.route('/login',methods=['POST'])
def login_post():  
     data="Your Email is : "+ request.form['email']
     data+="<br/>Your Password is : "+ request.form['password']
     return data

#register get and post method combined
@app.route('/register',methods=['GET','POST'])
def register():  
        if request.method == 'GET':
            return render_template('register.html',title='Register Page')
        else:
            data="Your Name is : "+ request.form['name']
            data+="<br/>Your Email is : "+ request.form['email']
            data+="<br/>Your Password is : "+ request.form['password']
            return data    

if __name__ == "__main__":  
    app.run()

In first line we are importing flask , render_template and request to do various tasks.
After homepage route is setup we are rendering index.html page stored in templates folder.

Note: You don’t need to specify folder like templates/index.html. Flask automatically load from it.

Again route for login page is setup at url /login and rendering login.html.As you can see default route method in flask is get,
so we don’t need to define get method.Also note we are passing a second variable via route method i.e. title of page which will be used by login.html.

Second login route we defined accepts post method and return data, which can be retrieved with the help of request.form method.

Register route is defined and it accepts both get and route simultaneously

@app.route('/register',methods=['GET','POST'])

I just wrote it to show that both get and post method can be defined on single route and conditional statement can be used.
So if method is post show data else get data from user .Something like that can be done in code.

    if request.method == 'GET':
            return render_template('register.html',title='Register Page')
    else:
            data="Your Name is : "+ request.form['name']
            data+="<br/>Your Email is : "+ request.form['email']
            data+="<br/>Your Password is : "+ request.form['password']
            return data

Finally we are running app via method app.run()

Note: app.run method accepts different parameters such as if you are running on remote server you can pass host and port.

Jinja2 Templating Engine

Flask uses Jinja2 as template engine. So in jinja2 There are two kinds of delimiters. {% … %} and {{ … }}
First one {% … %} is use to run statements such as if, for loop and second one {{ … }} is use to print out data or variable values.Thats why you will see something like this in login,register html files.

<title>{{title}}</title>  
<link rel="stylesheet" href="{{url_for('static', filename='bootstrap.css') }}" type="text/css">  

Here second delimiters is used to output variable “title” which was passed via route function.

Also you can see in stylesheet href we have used a variable something like {{url_for(‘static’, filename=’bootstrap.css’) }}
This is used to generate static files url and you must save static files in static folder in root directory of application.

Note: Again you don’t need to define static folder. Flask automatically uses it.

Thats why we have only used filename=’bootstrap.css’ in {{url_for(‘static’, filename=’bootstrap.css’) }}

If you are creating a css folder inside static folder you will be defining filename=’css/bootstrap.css’
Thanks for reading this post and for more info on Flask you can check out docs and even download as Pdf File

http://flask.pocoo.org/docs/



comments powered by Disqus