Tags

, , ,

A Web framework is a collection of packages or modules which allow developers to write Web applications or services without having to handle such low-level details as protocols, sockets or process/thread management. Sometimes you don’t need to eat everything served in the buffet. Infact, getting served only what you need is the best. This is what micro-frameworks provide.

According to Flask documentation (see references) , “Micro” does not mean that your whole web application has to fit into a single Python file, although it certainly can. Nor does it mean that Flask is lacking in functionality. … “Micro” does not mean that your whole web application has to fit into a single Python file, although it certainly can. Nor does it mean that Flask is lacking in functionality. The “micro” in microframework means Flask (or any micro-framework) aims to keep the core simple but extensible… can be everything you need and nothing you don’t.

In this post, we will see how to kick-start your mini-server to host a simple app using a micro-framework. First one will be Hello-World app, other one will show how to extract parameters and process them. We’ll save a detailed app for another post.

Installing and Getting Started

Install Flask. All you need to do is :

pip install Flask

and you are done. However Flask documentation suggests use of virtualenv and install flask within it. This isolates the environment and saves rest of the modules and libraries in case you blow anything while playing with the dependencies. Install virtualenv, activate it, and then install Flask inside it.


$ sudo apt-get install python-virtualenv
...
$ mkdir myproject
$ cd myproject
$ virtualenv venv
...
$ . venv/bin/activate
$ sudo pip install Flask

Voila! Done. Now we can begin our first “server”.

Saying Hello World!

We expect, the app’s homepage will say Hello to the viewers. The expected URL will be http://server/


from flask import Flask
app = Flask(__name__)

@app.route("/")
def Index():
    return "<h1>Hello World</h1>"

Save the script as hello.py and run it on terminal. Access the URL from a browser. http://127.0.0.1:5000/
It should say Hello World in a big bold.

Here’s what we just did. Import Flask from flask package. Create an object that will denote our app. Route the home URL ‘/’ to the function called Index() and say Hello World.

Playing a little more, you can create further URLs by assigning the route.


@app.route("/anotherHello")
def another():
    return "<h1>This is Another Hello World!</h1>"

Go to http://127.0.0.1:5000/anotherHello  and see the results.

Getting Parameters

You would want to put on some dynamism in your web app. A URL should read some data, do some processing and then give the results. Let’s create a method that will take two numbers from HTTP GET, compute their sum and print it to the user.


@app.route("/add", methods=['GET'])
def addParams():
 try:
     args = request.args
     print (args)
     no1 = args['a']
     no2 = args['b']
     no3 = int(no1) + int(no2)
     return ("<h2>Sum of "+str(no1)+" and "+str(no2)+" is "+str(no3)+"</h2>")
 except:
     return ("ERROR : Maybe some problem with the parameters")

So this time, we created another URL and mentioned that we’ll be accepting GET parameters through it. request.args gave us a dictionary of arguments, which we processed to compute the sum and print the results. Now you would go to a URL like:
http://127.0.0.1:5000/add?a=10&b=15

We added a try-except block here to save for the bad situations. User may give wrong or no parameters in the URL. So instead of giving Bad-Gateway error (502), we would print a message.

Where to go Further?

You can use Flask combined with other Python modules to create simple yet awesome apps. Flask also offers templates through which you can create full HTML files in which the data is later added dynamically by the script and rendered to the user. There are Signals that help you decouple applications by sending notifications when actions occur elsewhere in the core framework or another Flask extensions. Then there are views similar to Django views that offer better customization than templates.

Flask documentation explains patterns that can be used to create most web applications using Flask. There’s a lot to do. Just say hello world and create some awesome app.

References

Flask Documentation
Bottle (Another similar Web-Framework)
Significance of Large frameworks like Django v/s Microframeworks:
Nupul Kukreja on Quora