Contents

Hello Flask

Environment

MacOS 10.15.7 Catalina

1. Install

1
pip3 install Flask

2. HTTP GET

2.1 Composition

1
2
3
4
5
6
7
(main directory)
 ├app/
 │ ├templates/
 │ │ └index.html
 │ ├static/
 │ └app.py
 └run.py

2.2 Source code

app/run.py

1
2
3
4
from app.app import app

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

app/app.py

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

app = Flask(__name__)

# @app.route("/")
# def hello():
#    return "Hello Flask"
@app.route("/")
@app.route("/index")
def index():
    name = request.args.get("name")
    return render_template("index.html", name=name)

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

app/templates/index.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>Hello Flask</h1>

<h2>Get request</h2>
<p>{{name}} was sent</p>

</body>
</html>

2.3. run webserver

1
2
cd <main directory>
python3 run.py

Access to http://127.0.0.1:5000/index?name=abcdef

HTML on browser

../../../images/flask/hello-flask1.png


3. HTTP POST

Directory is the same with above sample.

3.1 Source code

app/app.py

Add below.

1
2
3
4
@app.route("/index",methods=["post"])
def post():
    user_id = request.form["user_id"]
    return render_template("index.html", user_id=user_id)

templates.html

Add below in <body> section.

1
2
3
4
5
6
<h2>Post request</h2>
<form action="/index" method="POST">
    <input type="text" name="user_id" placeholder="Enter User ID">
    <input type="submit" value="Submit">
</form>
<p>{{user_id}} was submitted</p>

3.2. run webserver

After re-run python3 run.py, you can see:

../../../images/flask/hello-flask2.png


References