[Python][Flask]Flask 基本實做

Flask 簡介

Flask. A web framework takes care of all the routing needed to organize a web page so that you don’t have to write the code yourself!

Why Flask?

  • First and foremost, you’ll be working with Flask because it is written in Python. You won’t need to learn a new programming language.
  • Flask is also a relatively simple framework, so it’s good for making a small web app.
  • Because Flask is written in Python, you can use Flask with any other Python library including pandas, numpy and scikit-learn. In this lesson, you’ll be deploying a data dashboard and pandas will help get the data ready.

基本樣板

# 檔案結構
|- webapp.py
# webapp.py
from flask import Flask

app = Flask(__name__) # __name__ 代表目前執行的模組

@app.route('/')
def index():
    return 'Index page'


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


if __name__ == '__main__':
     app.run(debug=True)
     # app.run(host='127.0.0.1', port=8000)

在開發的時候加上 app.run(debug=True) 讓程式調整的時候不需要每次重啟,所以在正式環境時不會設置。也可以寫成,app.debug=Trueapp.run()


@app.route()

介紹@app.route()前先了解 Python 的裝飾器(Decorator)@

Python 的 Decorator

# This is our decorator
def simple_decorator(f):
    # This is the new function we're going to return
    # This function will be used in place of our original definition
    def wrapper():
        print "Entering Function"
        f()
        print "Exited Function"

    return wrapper

@simple_decorator 
def hello():
    print "Hello World"

hello()

結果:

Entering Function
Hello World
Exited Function
def decorator_factory(enter_message, exit_message):
    # We're going to return this decorator
    def simple_decorator(f):
        def wrapper():
            print enter_message
            f()
            print exit_message

        return wrapper

    return simple_decorator

@decorator_factory("Start", "End")
def hello():
    print "Hello World"

hello()
Start
Hello World
End

route

route 的意思是「路;路線;路程;航線;路由」,在這裡則是指定網址的路徑。

因此,要將網址的路徑指定為hello則可以寫成

@app.route('/hello')

將 html 獨立出來

將 html 獨立出來撰寫,並使用 render_template() 讀取。flask 會從 templates 資料夾搜尋這個 html 檔案,並回傳。所以檔案的結構會是

# 檔案結構
|- templates
|   |_ index.html
|_ webapp.py
# webapp.py
from flask import Flask, render_template

app = Flask(__name__)

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


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


if __name__ == '__main__':
     app.run(debug=True)
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Flask frame work</title>
</head>
<body>
    <h1>I'm the best!</h1>
</body>
</html>

增加 html layout 與 css

# 檔案結構
|- static
|   |_ css
|       |_main.css 
|- templates
|   |- index.html
|   |_ layout.html
|_ webapp.py
/*main.css*/
body {
    font-family: sans-serif;
    margin: 0;
}
<!-- layout.html -->
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/main.css') }}">
    <title>{% block head %} {% endblock %}</title>
</head>
<body>
    {% block body %} {% endblock %}
</body>
</html>
<!-- index.html -->
{% extends "layout.html" %}
{% block head %}
    This is title
{% endblock head %}

{% block body %}
    <h1>Index Page</h1>
{% endblock body %}

Template Engine - Jinja


將 webapp.py 分解

# 檔案結構
|- run.py
|_ plotlyapp
    |- static
    |   |_ css
    |       |_main.css 
    |- templates
    |   |- index.html
    |   |_ layout.html
    |- __init__.py
    |_ routes.py
# run.py
from plotlyapp import app

if __name__ == '__main__':
     app.run(debug=True)
# __init__.py
from flask import Flask

app = Flask(__name__)

from plotlyapp import routes
# routes.py
from plotlyapp import app
from flask import render_template, url_for

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


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

執行 web app

python run.py

Reference: