Haven: Ram's Blog

March 26, 2020 • 5 min read

Learn Flask: Part 1

Flask Tutorial Image

“Study without desire spoils the memory, and it retains nothing that it takes in.” — Leonardo da Vinci

What is Flask?

Flask is a micro web framework that is developed using python at its base. It was created by Armin Ronacher of Pocoo, an international group of Python enthusiasts formed in 2004 as a simple wrapper around Werkzeug and Jinja and has become one of the most popular Python web application frameworks.

Prerequisites

  • Python 3
  • Installing packages through pip
  • Basic understanding of HTML and CSS

Installing Flask

Installing flask is rather simple, as it has no dependencies. You have to create a virtual environment either by using conda or venv. You can refer the original documentation here.

pip install flask

Getting Started

# app.py
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
    return "Hello World!"
if __name__ == '__main__':
    app.run(debug = True)

After installing flask, go to your project directory and create a file named app.py and paste the code above and execute it. You can view the result at http://127.0.0.1:5000/ or copy the ip address displayed in cmd to your browser. The output would be ‘hello world’ in the browser as seen in the hello function.

Let’s checkout the code, Flask with a capital “F” (as in: from flask import Flask) creates an object which refers to the entirety of the app itself: when we state app = Flask(**name**), we are creating the variable app which represents our application. Therefore, when we configure the variable app, we’re configuring the way our entire application works. For example, setting app = Flask() can accept a few attributes:

from flask import Flask
app = Flask(__name__,
            instance_relative_config=False,
            template_folder="templates",
            static_folder="static")

The attributes are the location of our config file, the templatefolder in which we’ll store html pages templates, and the staticfolder in which we’ll store front-end assets (JS, CSS, vendors, images, etc.)

@app.route("/") is a Python decorator that Flask provides to assign URLs in our app to functions easily. The decorator is telling our @app that whenever a user visits our app domain (app.com or http://127.0.0.1:5000/ in this case) at the given .route(), execute the home() function. Every web framework begins with the concept of serving content at a given URL. Routes refer to URL patterns of an app (such as myapp.com/home or myapp.com/about). Views refer to the content to be served at these URLs, whether that be a web-page, an API response etc. We can handle multiple routes with a single function by simply stacking additional route decorators above any route! The following is a valid example of serving the same “Hello World!” message for 3 separate routes:

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

Routing HTTP methods

@app.route() decorator also accepts a second argument: a list of accepted HTTP methods. Flask views accept GET requests by default, unless we explicitly list which HTTP methods the view should have. It is better a pass a parameter called methods which would contain a list of HTTP methods we need.

@app.route("/example", methods=['GET', 'POST', 'PUT'])

Dynamic Routes

Let’s talk about dynamically changing URLs based off a profile name or an article’s title. So, to do that we create a variable inside angle brackets <> and pass it to route().

@app.route('/<error>')
def pageNotFound(error):
    return ('Page '+ error +' not found! Please check the url!')
@app.route('/loggedin/<username>')
def profile(username):
    return (username +' has logged in')

You can also pass a specific type of variable after mentioning its type and using colon to separate it from the variable name.

@app.route('/<int:year>/<int:month>/<title>')
def article(year, month, title):
    return (title + 'was published in' + month + year)

Rendering HTML Pages

Flask renders web pages using jinja2 template, to do that we must first import a built-in function of Flask called render_template. render_template() is used to return html page to a route.

from flask import Flask, render_template
app = Flask(__name__,
           template_folder="templates")

Let’s now create an HTML file named index.html and paste the code below.

<!DOCTYPE html>
<html>
	<head>
		<title>
			Flask Tutorial
		</title>
	</head>
	<body>
		<h1>HTML template Works!</h1>
	</body>
</html>

index.html has a basic html layout with a header <h1> that contains some text. Let’s change our code in app.py to render index.html. Copy the code below and paste it in app.py.

from flask import Flask, render_template
app = Flask(__name__,
            template_folder="templates")
@app.route("/")
def home():
    """Serve homepage template."""
    return render_template('index.html')
if __name__ == '__main__':
    app.run(debug = True)

we can also pass values to our template as keyword arguments. For example, if we want to set the title and content of our template via our view as opposed to hardcoding them into our template, we can do so:

from flask import Flask, render_template
app = Flask(__name__,
            template_folder="templates")
@app.route("/")
def home():
    return render_template('index.html',
                           title='Flask-Login Tutorial.',
                           body="You are now logged in!")

Resources


Ram Shankar Choudhary

Personal blog of Ram Shankar Choudhary. I’m an engineering student working on various projects. I learn in public and write about everything I know.

You may follow me on twitter or join my newsletter for latest updates.