Skip to content

Getting Started

Result

Flask is the best micro web framework written in Python 🔥

Installation

1
$ pip install -U flask
  • Open your favourite code editor 😍
  • Create a new *.py file ✅
  • Import Flask from the flask framework and define your app:
1
2
3
from flask import Flask

app = Flask(__name__)
  • __name__ is the import name for our flask app

Create simple view function that returns simple text/html response:

1
2
3
4
5
6
7
8
from flask import Flask


app = Flask(__name__)


def home_view():
    return "Hello Bro 👋"

Next, you will should add this view function on your app's url rules. For this, we have to use Flask's add_url_rule method:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
from flask import Flask


app = Flask(__name__)


def home_view():
    return "Hello Bro 👋"


app.add_url_rule(
    rule="/",
    view_func=home_view
)

flask.Flask.add_url_rule

  • rule should be str
  • view should be function or class For class based views, Flask has as_view method.

Routes

The method of add_url_rule is used by flask developers very rarely. They use route decorator instead of using add_url_rule and it provides to assign URLs in our app to functions easily.

1
2
3
@app.route("/")
def home_view():
    return "Hello Bro 👋"
  • "/" - url that our view function returns response.

route decorator also uses from add_url_rule method :

ROUTE_DECORATOR

From flask's source code

You can return any of the string and binary related types: str, unicode , bytes , bytearray, or if you prefer, you can return an already built response object:

1
2
3
4
5
6
7
from flask import Response

app = Flask(__name__)

@app.route("/")
def function():
    return Response(...)

View Functions

The names we chose for our view functions should be unique.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
@app.route("/")
def home():
    return "Hello!"

@app.route("/home")
def home():
    return "Hello from home_2!"

# AssertionError:
# View function mapping is overwriting an existing endpoint function: :view_function_name:
Back to top