# 前言
在大學和碩士期間主要都是接觸深度學習和電腦視覺的方面的研究,但最近慢慢發現,除了要會這些,許多公司也更重視如何把模型的結果接上後端的API或APP來做使用。但我對製作API或APP是完全沒有概念的,所以這是開始學習製作API和APP的第一天。
這是我的學習紀錄,所有範例都是跟著[Book_Python Flask實作記錄](https://hackmd.io/GVo6X6LoS3GNIW50LBJytw)的教學,並使用我自己的方法整理,以及加上自己的看法。
# 說明
成功登入或提交的文件格式有問題等,系統需要讓使用者之後這個情況,而flask中可以利用flash可將訊息由後端傳至前端。
延續[從零開始學Flask #09 redirect after some actions](https://hackmd.io/xfQ18MXlRDejua_EmShcjA)的範例,使用者輸入帳號密碼,並通過驗證成功登入之後,丟出一個訊息告知使用者登入成功。
- 直接import```flash```
```python=
from flask import flash
```
- 修改python文件
```python=
from flask import Flask, request, redirect, url_for, render_template, flash
# 固定格式
app = Flash(__name__)
@app.route('/loginurl', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
# 檢查帳號密碼
if check(request.form['username'], request.form['password']):
# 丟出成功訊息
flash('Login Success')
# 跳轉畫面
return redirect(url_for('hello', username=request.form.get('username')))
retrun render_template('10_login.html')
# 檢查帳號密碼
def check(username, password):
if username == "admin" and password == 'hello':
return True
else:
return False
@app.route('/hello/<username>')
def hello(username):
return render_template('10_hello.html', username=username)
if __name__ == "__main__":
app.run(debug=True)
```
第12行:成功登入,丟出訊息
第14行:同樣透過```redirect```重新導向到```url_for('hello')```,並傳遞參數```username```。
第19行:檢查帳號密碼function
- 調整10_hello.html
```html=
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello</title>
</head>
<body>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul class="flash">
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
hello, {{ username }}, Welcome my homepage!
</body>
</html>
```
第8行:```get_flashed_messages```會將所有```session```內的所有```messag```e取出
第9行:判斷是否有```message```
第11行:由於```get_flashed_messages```是將有所訊息取出,因此要透過```for```來取得個別訊息
- 調整10_login.html
```html=
<form method="post" action={{url_for('login')}}>
<p>
<input type="text" name="username">
</p>
<p>
<input type="text" name="password">
</p>
<p>
<button type="submit">
Submit
</button>
</p>
</form>
```
第6行:新增輸入密碼的區塊
<br>
==執行後會發生這個錯誤,如下圖所示:==

**NOTE:** 這個問題是因為在flask只要用到session,就需要一組key作加密,避免資訊安全的問題
- 對python文件做調整
```python=
if __name__ == "__main__":
app.secret_key = "Your Key"
app.run(debug=True)
```
<br>
==重新執行,並登入,如下圖所示:==

==跳轉畫面結果與丟出訊息,如下圖所示:==

<br>
**NOTE:** 在HTML的文件中提到,get_flashed_messages會將session內的message全部取出,但這個形式只限於「這一次」的執行中。重新整理頁面後,訊息就會消失,不需要擔心被其他登入的使用者攔截。
==重新整理頁面後,訊息就會消失,如下圖所示:==

<br>
[Source Code Please Visit](https://github.com/ChrisCodeNation/How-to-Make-an-API-with-Flask-Course/blob/main/10_flash_message.py)