Flask - Part 1


Introduction

Welcome to the first part of my flask course.

In this part we’ll build a super simple flask app.

1 - Creating our environment

Let’s create a dedicated folder for our app.

# assuming you are in flask_learning
mkdir my_app_v1
cd my_app_v1

2 - Discovering Flask

Flask is a python web micro-framework. What can Flask help you with ? Quickly building a web-app.

2.1 - Coding our first app

Let’s build this dead-simple flask app.

# assuming you are in flask_learning/my_app_v1
virtualenv venv -p python3 #create the venv
source venv/bin/activate # enter the venv
pip install flask 
pip freeze > requirements.txt # save the list of dependencies into requirements.txt
# (venv)
touch app.py

Let’s code in app.py :

# app.py

from flask import Flask
app = Flask(__name__)


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

Nothing fancy here, we just created a route accessible at ‘/’ and told flask to return ‘Hello, World!’ if someone requests this route.

2.2 - Running our first app

Let’s launch this app :

# assuming you are in flask_learning/my_app_v1
# (venv)
FLASK_ENV=development FLASK_APP=app.py flask run --host=0.0.0.0 --port=5000

v1 flask run example

So what’s going on here ?

We told flask:

2.3 - Testing our app

To try and test your first route, many tools are available.

I personnaly use these two :

2.3.1 - Testing with postman

v1 postman example

Our request worked and we received “Hello, World!” so all good.

2.3.2 - Testing with httpie

v1 httpie example

Everything is working great :-)

Conclusion

We just saw how to create a route, how to launch our server and how to test this route with postman and httpie.

If you’re stuck or don’t understand something, feel free to drop me an email / dm on twitter / a comment below. You can also take a look at flask_learning/flask_cybermooc/version_1 to see the reference code. And use run.sh to launch it.

If you understood everything, you’re now ready to go to part 2 where you will learn how to connect a database to your app.


COMMENTS