Introduction to Flask :)

Prerequisite

First thing we want to do is to install pip: https://pypi.python.org/pypi/pip

Now we will install Flask: pip install Flask

Basic Server

from flask import Flask

app = Flask(__name__)

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

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

Time to run

python app.py

// Its now running on our machine, only visible locally.

* Running on http://127.0.0.1:5000/

To make it publically visible add:

app.run(host='0.0.0.0')

To turn on debug (to automatically refresh on saving):

app.run(debug=True)

Routing

@app.route('/')
def index():
return 'Index Page'

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

Passing variables to the routes

@app.route('/user/<username>')
def show_user_profile(username):
# show the user profile for that user
return 'User %s' % username


@app.route('/post/<int:post_id>')
def show_post(post_id):
# show the post with the given id, the id is an integer
return 'Post %d' % post_id

Now lets render a template

from flask import render_template

...

@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html', name=name)

Create a template folder and hello.html inside it

/app.py
/templates
/hello.html

in hello.html

<!doctype html>
<title>Hello from Flask</title>
{% if name %}
<h1>Hello {{ name }}!</h1>
{% else %}
<h1>Hello World!</h1>
{% endif %}

Return json for an api

from flask import jsonify
...
@app.route('/get_json')
def get_json():
return jsonify(name='Brian',
last_name='Brian')