# Flask
###### tags: `人生苦短,我學Python`
## 特性
* 免費
* 內建伺服器與偵錯器
* 偵錯器的功能強大
* 使用Unicode編碼
* 使用Jinja2模板
* 提供test_client()函式測式介面
## 架構
* 開始使用Flask
```python=
pip install Flask
```
* 隨意建立資料夾(Python-falsk)
```python=
#1.py(測試用)
from flask import Flask
app = Flask(__name__)
#路由
if __name__ == '__main__':
app.run()
```
## 建立路由
* 語法
```python=
#@為裝飾器
@app.route('網頁路徑')
def 函式名稱:
處理函式
```
* route為路徑
```python=
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return '首頁'
@app.route('/hello')
def hello():
return '歡迎頁面'
if __name__ == '__main__':
app.run()
```


* 多網址對應相同函式
```python=
@app.route('/')
@app.route('/hello')
def index():
return '首頁'
```
* app.run()參數
```python=
app.run(host = '0.0.0.0', port = 80, defug = false)
#host的預設值為127.0.0.1,當網站開發完成時,需改成0.0.0.0
#port設定埠號,預設為5000
#debug須改為true,網站開發完成時須改為false,否則網站會有重大安全疑慮
```
* 動態路由
```python=
@app.route('網頁路徑/<資料型態:參數>/<......>')
```
* example
```python=
#網頁必須符合參數
@app.route('/hello/<string:name>')
def hello(name):
return '{}你好'.format(name)
```

## 用get及post方式傳送資料
* get傳送參數
第一參數以「?」符號連接,第二個以後的參數都以「&」連結
```shell=
網址?參數1=值1&參數2=值2...
```
* example
```python=
http://127.0.0.1:5000/hello?name=rex&tel=0348521677
```
* flask接收get方式傳送的資料(methods)
```python=
@app.route('./path', methods = ['GETS'])
```
* 接收get參數
```python=
#匯入模組
from flask import request
```
* 匯入模組後就可以使用args.get方法
```python=
request.args.get('參數')
```
* example
```python=
from flask import Flask
from flask import request
app = Flask(__name__)
@app.route('/', methods = ['GET'])
def index():
name = request.args.get('name')
return '{}你好'.format(name)
if __name__ == '__main__':
app.run()
```

--------------------------------------------
* 使用post的方式傳送資料
* post的方式傳送的資料不會顯示在網址列,基本上是使用表單的方式
* 接收post參數
```python=
#匯入模組
from flask import request
```
* 取得參數值
```python=
request.values('參數名稱')
```
* example
```python=
from flask import Flask
from flask import request
app = Flask(__name__)
@app.route('/', methods = ['GET', 'POST'])
def submit():
if request.method == "POST":
username = request.values['username']
password = request.values['password']
if username == 'rex' and password == '1234':
return '歡迎'
else:
return '錯誤'
return """
<form method = 'post' action = ''>
<p>帳號:<input type = 'text' name = 'username' /></p>
<p>密碼:<input type = 'text' name = 'password' /></p>
<p><button type = 'submit'>確認</button></p>
</form>
"""
if __name__ == '__main__':
app.run(debug = True)
```

## 使用模板
* 使用render_template模板讀取網頁檔
```python=
#匯入
from flask import render_template
```
* 語法
```python=
render_template('網頁檔案名稱')
```
* 須放在名為templates的資料夾中
```htmlembedded=
//hello.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf8">
<title>first web</title>
</head>
<body>
<h1>my web</h1>
<h2>web</h2>
</body>
</html>
```
* 將剛才的python程式碼改成
```python=
from flask import Flask
from flask import render_template
app = Flask(__name__)
@app.route('/hello')
def hello():
return render_template('hello.html')
if __name__ == '__main__':
app.run()
```
* 結果

* 傳送參數及變數
```python=
#傳送name字串
@app.route('/hello/<string:name>')
```
* render_template加入第二個參數
```python=
#**locals()為傳送所有的變數+參數
render_template('xxx.html', **locals())
```
* 接收須以{{ }} 包圍起來
```javascript=
{{ name }}
```
* 範例
```htmlembedded=
//hello.html
<h2>{{ name }}</h2>
<h3>{{ now }}</h3>
```
```python=
#your python code
from flask import Flask
from flask import request
from flask import render_template
from datetime import datetime
app = Flask(__name__)
@app.route('/hello/<string:name>')
def hello(name):
now = datetime.now()
return render_template('hello.html', **locals())
if __name__ == '__main__':
app.run()
```
* 結果

## 使用圖片等靜態檔案
* 一般會放在static的資料夾中
```htmlembedded=
{{ url_for('static', filename = 檔案) }}
```
* example
```htmlembedded=
//hello.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf8">
<title>first web</title>
<link rel="stylesheet" href="{{ url_for('static', filename = 'style.css') }}"/>
</head>
<body>
<h1>my web
<img src="{{ url_for('static', filename = 'art.jpg') }}" width="50" height="150" />
</h1>
<h2>{{ name }}</h2>
<h4>{{ now }}</h4>
</body>
</html>
```
```css=
#static/style.css
h4{
color: blueviolet;
}
```
* 結果

## template語言
| 變量| 將views傳送內容至模板指定的位置上 | {{ username }} |
| -------- | -------- | -------- |
| 標籤 | if / for | {% if found %} and {% for item in items %}|
|單行註解 |{# 註解 #} |{# 註解 #}|
|文字|HTML標籤或文字| title |
* example
```htmlembedded=
//hello.html
<h2>{{ student.學號 }}</h2>
<h4>{{ kind.1 }}</h4>
```
```python=
from flask import Flask
from flask import request
from flask import render_template
from datetime import datetime
app = Flask(__name__)
@app.route('/hello')
def hello():
#字典
student = {'學號':"10911210", "姓名":"荷葉"}
#陣列
kind = ['good', 'bad']
return render_template('hello.html', **locals())
if __name__ == '__main__':
app.run(debug = True)
```
* 結果

* 標籤範例
```htmlembedded=
//hello.html
{% if student.學號 == '10911210' %}
<h1>相同</h1>
{% endif %}
```
* 結果

* 附贈for迴圈
```htmlembedded=
//hello.html
{% for i in kind %}
{{ i }}
{% endfor %}
```
* 接收串列資料
```python=
person1 = {'name' : 'rex', 'phone' : '0935120455'}
person2 = {'name' : 'andy', 'phone' : '093564520455'}
person3 = {'name' : 'bad', 'phone' : '093464556455'}
persons = [person1, person2, person3]
```
```htmlembedded=
//hello.html
<h3>
{% for person in persons %}
<ul>
<li>{{ person.name }}</li>
<li>{{ person.phone }}</li>
</ul>
{% endfor %}
</h3>
```
* 結果

{%hackmd S1DMFioCO %}