[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=True
、app.run()
。
@app.route()
介紹@app.route()
前先了解 Python 的裝飾器(Decorator)@
。
Python 的 Decorator
- 文章:Python進階技巧 (3) — 神奇又美好的 Decorator ,嗷嗚!
- general decorators tutorial: Primer on Python Decorators
- In Python, the @ symbol is used for decorators.
- A decorator is just a function which takes in a function (the one which you decorated with the “@” symbol) and returns a new function.
# 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')
- 更多
@app.route()
的用法:Flask Tutorial: Routes
將 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
- Jinja is a web Template Engine for Python
- Jinja is Flask’s default template engine
- 透過 Template Engine(模板引擎)可以在靜態的 HTML 加入變數,動態的 render 出 HTML,動態建立HTML
- 可以使用變數、條件、迴圈來撰寫更簡潔的 code,能夠更輕鬆的維護程式碼
- 常用語法
- comments:
{# comments #}
- variables
{{ post.title }}
- dictionary:
{{your_dict['key']}}
- list:
{{your_list[0]}}
- 多行代碼:
{% 開始 %} HTML標籤 {% 結束 %}
- comments:
- 一篇文章搞懂Jinja2 Template Engine 模版引擎
- Day8– 前端小字典三十天【每日一字】– Template Engine
將 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: