Begin with Flask

Lecturer: 夜猫

OUTLINE

  • What is Flask?
  • Environment
  • Basic App Structure
  • Template

What is Flask?

  • The microframe wrote by Python
  • Based on WSGI、Werkzeug、Jinja2
  • Use simple kernel, and extend other functions by extensions
  • System Management
  • Extension
  • Template

Environment

Create a new folder as the project root directory

$ mkdir newproj
$ cd newproj

Then we are going to install Flask, but before we get start it, we shall install virtual environment first.

If you use Linux, then enter the following instruction to install venv

$ sudo apt-get install python3-venv

Create the virtual Environment with the folloing command

$ python -m venv [virtual environment name]

"-m venv" will make the virtual environment as an independent script

As soon as you create the virtual environment, active it.

$ venv\Scripts\activate            // Windows
$ source venv/Scripts/activate     // Linux or Mac OS

If you go well so far, you should have the scene like:

(venv) $ 

And if you want to stop the virtual environment

(venv) $ deactivate

Now, install Flask

(venv) $ pip install flask

Basic App Structure

Before we start coding, we should know that every Flask microframework must has an app.

So creates a file named hello.py and has the folloing code in it.

from flask import Flask
app = Flask(__name__)

Then we should know that every client will send requests from their own browser to Flask app, which means the app must know how to deal with these requests from every URL.

The relationship between URL and the function, which respond the request, is called route.

Definition:

# Static
@app.route('/')
def index():
    return '<h1>Hello World!</h1>'

# Dynamic
@app.route('/user/<name>')
def user(name):
    return '<h1>Welcome to SIRLA, {}!</h1>'.format(name)

Warning: This program is used only for example, we should not code like this.

# hello.py
from flask import Flask
app = Flask(__name__)

@app.route('/')
def index():
    return '<h1>Hello World!</h1>'

@app.route('/user/<name>')
def user(name):
    return '<h1>Welcome to SIRLA, {}!</h1>'.format(name)

Execute the web server:

(venv) $ set FLASK_APP=hello.py
(venv) $ flask run
* Serving Flask app "hello"
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
(venv) $ export FLASK_APP=hello.py
(venv) $ flask run
* Serving Flask app "hello"
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Windows

Linux / Mac OS

Template

<!DOCTYPE html>
<!-- index.html -->
<html>
<head>
    <title>Index</title>
</head>

<body>
    <h1>Hello World!</h1>
</body>
</html>
<!DOCTYPE html>
<!-- user.html -->
<html>
<head>
    <title>User Page</title>
</head>

<body>
    <h1>Hello, {{ name }}!</h1>
</body>
</html>

Write the two new template that seems the same as former example.

New a directory named templates and put all templates in it.

Create a new Flask app named app.py.

from flask import Flask, render_template
app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/user/<name>')
def user(name):
    return render_template('user.html', name=name)

EXECUTE THE PROGRAM AGAIN!

We've all already known about Bootstrap, so now we're going to use bootstrap to beautify out website.

In Flask, we use Flask-bootstrap to achieve the effect what we want.

First, install the extension:

(venv) $ pip install flask-bootstrap

Then new the following code into web.py to initialize bootstrap:

from flask_bootstrap import Bootstrap
# ...
bootstrap = Bootstrap(app)

Before we go on, we will talk about inherit.

We use the concept of inherit because a website have several pages, and each page has the same template.

Write the base_index.html as basic template, and define the block which can be written by the latter program that inherit it.

We use blockendblock to define the blocks.

Then open index.html to modify it.

<!-- base_index.html -->
<!DOCTYPE html>
<html>
<head>
    {% block head %}
    <title>
        {% block title %}{% endblock %} - My Application
    </title>
    {% endblock %}
</head>

<body>
    {% block body %}
    {% endblock %}
</body>
</html>
{% extends "base_index.html" %}
{% block title %}Index{% endblock %}
{% block head %}
    {{ super() }}
    <style>
    </style>
{% endblock %}
{% block body %}
    <h1>Hello, World!</h1>
{% endblock %}

"extend" declared that this program extend by base_index.html.

"super()" means quote the basic template contents.

Same concept with bootstrap.

As soon as we initialize flask-bootstrap, we can use its basic template.

Open user.html to modify it:

{% extends "bootstrap/base.html" %}
{% block title %}Flasky{% endblock %}
{% block navbar %}
<div class="navbar navbar-inverse" role="navigation">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="/">Flasky</a>
        </div>
        <div class="navbar-collapse collapse">
            <ul class="nav navbar-nav">
                <li><a href="/">Home</a></li>
            </ul>
        </div>
    </div>
</div>
{% endblock %}

{% block content %}
<div class="container">
    <div class="page-header">
        <h1>Hello, {{ name }}!</h1>
    </div>
</div>
{% endblock %}

Flask also allowes us to define the customize error page.

The most error we will meet:

  1. 404 - Page Not Found
  2. 500 - Internal Server Error

We use app.errorhandler to define the function.

New the following code into web.py

@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404

@app.errorhandler(500)
def internal_server_error(e):
    return render_template('500.html'), 500

Then we are going to write 404.html and 500.html.

Since we want it look like others website, we have two ways:

  1. The simplest way that copy user.html to error pages, then modify the contents.
  2. Create a base.html then inherit it.

Unfortunately, we are going to use the second way.

So, first, new a file named base.html

{% extends "bootstrap/base.html" %}
{% block title %}Flasky{% endblock %}
{% block navbar %}
<div class="navbar navbar-inverse" role="navigation">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                <span class="sr-only">Tooggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="/">Flasky</a>
        </div>
        <div class="navbar-collapse collapse">
            <ul class="nav navbar-nav">
                <li><a href="/">Home</a></li>
            </ul>
        </div>
    </div>
</div>
{% endblock %}

{% block content %}
<div class="container">
    {% block page_content %}{% endblock %}
</div>
{% endblock %}

In this template, there is a page_content in the middle of content which can be defined by the latter pages.

Write 404 error page.

<!-- 404.html -->
{% extends "base.html" %}
{% block title %}Flasky - Page Not Found{% endblock %}
{% block page_content %}
<div class="page-header">
    <h1>404 - Page Not Found</h1>
</div>
{% endblock %}

LAB - Write 500 error page

<!-- 500.html -->
{% extends "base.html" %}
{% block title %}Flasky - Internal Server Error{% endblock %}
{% block page_content %}
<div class="page-header">
    <h1>500 - Internal Server Error</h1>
</div>
{% endblock %}

LAB - Base on base.html, modify user.html

<!-- user.html -->
{% extends "base.html" %}
{% block title %}Flasky{% endblock %}
{% block page_content %}
<div class="page-header">
    <h1>Hello, {{ name }}!</h1>
</div>
{% endblock %}

Integration

# 啟動虛擬系統
$ venv\Scripts\activate         # Windows用這個
$ source venv/Scripts/activate  # Linux跟Mac OS用這個

# 關閉虛擬系統
(venv) $ deactivate

# 啟動Flask 
(venv) $ export FLASK_APP=[你設定路由的.py檔]    # Windows的寫法:將export改成set
(venv) $ flask run
from flask import Flask, render_template    # 引入Flask基本套件跟模板使用套件
from flask_bootstrap import Bootstrap       # 引入Bootstrap套件
app = Flask(__name__)                       # Flask初始化
bootstrap = Bootstrap(app)                  # Bootstrap初始化

# 以下為路由的設定
# ...

Title Text

Begin with Flask

By Иo1lz

Begin with Flask

  • 170