Wednesday, March 6, 2013

Flask


      Flask is a lightweight web application framework written in Python. Flask is called a microframework because it keeps the core simple but extensible. Helps both for development and deployment of web applications. Flask depends on two external libraries, Werkzeug and Jinja2. Werkzeug is a toolkit for WSGI, the standard Python interface between web applications and a variety of servers for both development and deployment. Jinja2 renders templates. Flask application can test in local machine by using local server. Then finally you can deploy it on web server.This post gives a good introduction to Flask.

Installation:

Install flask in your local machine using the command:

sudo apt-get install python-flask

Simple App: Hello world

simple Flask application looks like this:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World!'

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

In this code first we imported the flask class.first argument is the name of the application's module.if you are using single module, you should use __name__. Next we create an instance of this class. we pass it the name of module. This is needed so that Flask knows where to look for templates, static files and soon. Then route() decorator is used to bind a function to URL

Just save it as hello.py and run with your Python interpreter. The local server is now running
$ python hello.py
    * Running on http://127.0.0.1:5000/

You should see your hello world message on http://127.0.0.1:5000/
To stop the server, use Control-C

STUDENTS APPLICATION IN FLASK

In this tutorial  we will create a simple web application 'student details'. The student details application provide you entering details of students and get back all data by sorting order by age and mark, also provide remove option and search option. We will use Flask and SQLite database with Python.

 Creating Folders


Before we get started, let’s create the folders needed for this application where we drop our files:
/students-app
       /static
       /templates



Directly into this folder we will then put our database schema as well as main module
in the following steps. The files inside the static folder are available to users of the
application via HTTP. Inside template folder Flask will looks for templates.

 Database


First we want to create the database 'students.db' .The sqlite3 data base system had used for handling datas.For this application only a single table is needed and we only want to support SQLite so that is quite easy.The database is created using the link:
http://zetcode.com/db/sqlitepythontutorial/

The code used for storing data in data base is given below. The datatostore may a variable, list, tuple etc. Don't forget to import sqlite3 from Python library.

con = sqlite3.connect('students.db')
        cur = con.cursor()
        cur.execute("CREATE TABLE IF NOT EXISTS student(name text, sex text, age text, mark text)")
        cur.execute("INSERT INTO student VALUES(?, ?, ?, ?)", data)
        con.commit()
        con.close()

in this code first connected to the database students.db file. From the connection, we get the cursor object. The cursor is used to traverse the records from the result set.We call the execute() method of the cursor and execute the SQL statement. execute method is used for table creation and insert datas in it. the changes must be committed using the commit() method. In the final step, we release the resources.

Show Entries


For displaying retrieved data in specific format you should use templates. the templates can handle variables.so it is very easy to handle retrieved data in specific order.

cur.execute("SELECT * FROM student")
rows = cur.fetchall()
entries = [dict(name=row[0], sex=row[1], age=row[2], mark=row[3]) for row in rows] return
render_template('show.html', entries=entries) 
the SQL statement SELECT * FROM selects all data from student table.The fetchall() method gets all records. It returns a result set. Technically, it is a tuple of tuples. We print the data to the console, row by row.where the entries are passed to the template show.html.render_template is used for rending template into page.

The template show.html :

<!doctype html>

<link rel=stylesheet type=text/css href="{{ url_for ('static', filename = 'style.css')}}">
<div class=metanav>
<p><a href="/">Home</a></p>
</div>
<h1>STUDENTS DETAILS</h1>
{% block body %}
  <ul class=entries>
  {% for entry in entries %}
    <li>{{ entry.name }} {{entry.age|safe}} {{entry.sex|safe}} {{entry.mark|safe}}
  {% else %}
    <li><em><center>Unbelievable.  No entries here so far...!</em></center>
  {% endfor %}
  </ul>
{% endblock %}

HTTP method


HTTP knows different methods for accessing URL.We use two methods in this example, GET and POST.

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

By default, a route only answers to GET requests, but that can be changed by providing the methods argument to the route() decorator.Using GET request The browser tells the server to just get the information stored on that page and send it and POST request is used for telling the browser  the server that it wants to post some new information to that URL and that the server must ensure the data is stored and only stored once.

For running the application use the command:


python students.py


The local server is now running visit http://127.0.0.1:5000/. You can see application in your browser.

if you want full source code, check out the link: https://github.com/jaseemkp/flask-students-app/archive/master.zip 

No comments:

Post a Comment