Flask Quickstart

Cho Zin Thet
6 min readSep 16, 2021

Python web framework

Flask is a famous python web framework. Another popular framework is Django. If you are very new to web, you should choose Flask because it is easier and simple than Django. But Django is good for larger and complex web application.

Before Flask, should know about basic python and frontend web development HTML, CSS

Run Sample Flask app

create a folder and in folder create main.py

from flask import Flask

app = Flask(__name__)
app.config['ENV'] = 'development'

# creating route
@app.route("/")
def home():
return "<p>Hello, World!</p>"

Run In command

set FLASK_APP=main.py
set FLASK_ENV=development
flask run

Run In Bash

export FLASK_APP=main.py
export FLASK_ENV=development
flask run

we set FLASK_APP to tell flask which file to run and set FLASK_ENV. We will learn later and run flask

or

from flask import Flaskapp = Flask(__name__)
app.config['ENV'] = 'development'
# creating route
@app.route("/")
def hello_world():
return "<p>Hello, World!</p>"
if __name__ == "__main__":
app.run(debug=True)

the same as above example. run python file

python main.py

Basic route

create a folder and in folder create main.py

from flask import Flaskapp = Flask(__name__)# creating route
@app.route("/")
def home():
return "<p>Hello, World!</p>"
if __name__ == "__main__":
app.run(debug=True)

run

python main.py

above code will run on http://127.0.0.1:5000/ and you will see Hello, World! because we create home route that return Hello, World!

localhost:5000
  • import Flask class from flask
  • Flask parameter should be a module name. and we pass __name__
  • __name__ is special variable. you can test print(__name__) and it will print __main__. __main__ means you run directly the file or if you get module name, you imported another file.
  • @app.route(“/”) is decorator function that return home function
  • “/” means “http://127.0.0.1:5000/” and “/test” means “http://127.0.0.1:5000/test”
  • return test will print on the “/” route. That’s why Hello, World! print on http://127.0.0.1:5000/
  • the last if statement is that if you run directly file, run the application.
  • debug=True means if there is an error, error will be shown on page.

If you get WARNING, don’t worry we will set ENV(environment) in ENV

URL Variables

passing variables in url

create add route that pass data variable. variable pass to add function as arguments and print that variable

@app.route("/add/<data>")
def add(data):
print(data)
return "add.html"

go to http://127.0.0.1:5000/add/food and you will see “food ”in command

Rendering Templates

create templates folder and create html files in there (flask will look for templates in templates folder)

from flask import Flask, render_template, redirect, url_for, request

app = Flask(__name__)

@app.route("/")
def home():
return render_template("home.html")


@app.route("/add/<data>")
def add(data):
print(data)
return render_template("add.html")


@app.route("/update")
def update():
return render_template("update.html")


@app.route("/delete")
def delete():
name = request.args.get("name")
print(name)
return redirect(url_for('home'))


if __name__ == "__main__":
app.run(debug=True)

Redirect and url_for

above example “/delete” route redirect the “/home” route

@app.route("/delete")
def delete():
name = request.args.get("name")
print(name)
return redirect(url_for('home'))

or

@app.route("/delete")
def delete():
name = request.args.get("name")
print(name)
return redirect("/home")

API requests

requesting API with python requests methods

requests.methods (requests.get(), requests.post(), requests.put(), requests.patch(), requests.delete())

import requestsresponse = requests.get("https://jsonplaceholder.typicode.com/users", params={"email":'Shanna@melissa.tv'})
response_data = response.json()
print(response_data)

Practice for creating API and API requests

HTTP Methods

Creating allow methods in each route for HTTP request. HTTP request can be from api request (I show in previous API part) and form request. We will catch user input value with request object and read more about that in next part.

This is add route that allow two HTTP methods GET and POST. And you can see user HTTP request methods with (request.methods).

@app.route("/add", methods=['GET', 'POST'])
  • GET
  • POST
  • PATCH
  • PUT
  • DELETE
from flask import Flask, render_template, redirect, url_for, request@app.route("/add", methods=['GET', 'POST'])
def add():
print(request.method)
return render_template("add.html")

Practice for HTTP request with form input

Request Object

Request object get HTTP request (request header, request methods, request url arguments, request form inputs)

Import request

from flask import request

Get request method

In this login route, login allow HTTP ‘GET’ request and ‘POST’ request.

If ‘GET’ request, return render login.html (jinja template)

If ‘POST’ request, get form data and redirect to success page and pass email arguments in URL. The URL become like this

http://127.0.0.1:5000/success?email=xawyk%40mailinator.com

@app.route("/login", methods=['GET', 'POST'])
def login():
if request.method == 'POST':
print(request.form['email'])
print(request.form['password'])
return redirect(url_for("success", email=request.form['email']))
return render_template("login.html")

login.html

<div class="form_container">
<form class="form_2" method="POST" action={{url_for("login")}}>
<div class="input_fields">
<h1>User Login</h1>
<input type="text" name="email" id="name" placeholder="Name" required>
<input type="password" name="password" id="password" placeholder="Password" required>

</div>
<button type="submit" class="outline_md_btn">
Submit
</button>

</form>
</div>

Get form data

request.form['name']

Get files from request

request.files['upload']

Get cookies from request

request.cookies.get('auth_token')

Get request arguments

Url ➜ http://127.0.0.1:5000/success?email=xawyk%40mailinator.com

@app.route("/success")
def success():
print(request.args['email'])
return render_template("success.html")
from flask import request

Get Request Header

request.headers will show the header of HTTP request. User login or sometime request can be passed with user data in headers and we can check like this.

@app.route("/success")
def success():
print(request.headers)
print(request.args['email'])
return render_template("success.html")

Response

RETURN value automatically response with response status code and json data (jsonify) or text or html templates.

return template

@app.route("/")
def home():
return render_template("home.html")

return text

@app.route("/")
def home():
return "home"

return json

@app.route("/users")
def user():
return jsonify({'name': 'sofia', 'email': 'sofia@gmail.com'})

Make response

If you want to modify response data, you can use make_response() as response.

response = make_response(render_template('home.html'))
response.set_cookie('auth_token', encoded_jwt.decode())
return response, 201

Static Files

create static folder and add styles.css

styles.css

body {
background-color: coral;
}
h1{
color: red;
}

home.html

css link ➜ static/styles.css

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- CSS -->
<link rel="stylesheet" href="static/styles.css">
<title>Document</title>
</head>
<body>
<h1>This is Home Page</h1>
</body>
</html>

If css file doesn’t work, right click to reload button and hard reload

hard reload

Error Handling

Instead of returning error, “Page Not Found” will show as 404 error.

@app.route('/download')
def download():
flask.abort(404)
@app.errorhandler(404)
def page_not_found(error):
return "Page Not Found"

Configuration

We can set different config values base on application environments.

config values ➜ ENV, DEBUG, SECRET_KEY

print(app.config)

Add new value

app.config['SECRET'] = "secret"
print(app.config)

ENV config

Production

ENV config value is which environment you app is running. Default ENV is production. Run production server when deploy

app.config['ENV'] = 'production'

Development

development mode reload the code when it is changed.

When you run flask you will see above warning. Then set below code

app.config['ENV'] = 'development'

Set configuration values depend on application environment

  • create config.py
class Config(object):
DEBUG = False
TESTING = False
class ProductionConfig(Config):
ENV = 'production'
class DevelopmentConfig(Config):
ENV = 'development'
DEBUG = True

means that in production server ENV is production. In development server ENV is development and debug mode is true.

You can set more config values.

  • in main.py
from flask import Flaskapp = Flask(__name__)
app.config.from_object("config.DevelopmentConfig")
@app.route('/')
def home():
return "home"
if __name__ == "__main__":
app.run()

--

--