Flask訊息閃現及日誌記錄
阿新 • • 發佈:2019-01-31
訊息閃現
Flask 提供了一個非常簡單的方法來使用閃現系統向用戶反饋資訊。閃現系統使得在一個請求結束的時候記錄一個資訊,然後在且僅僅在下一個請求中訪問這個資料。Flask訊息閃現可以給使用者更好的體驗。比如,我們改造一下上一篇中的上傳圖片程式碼,加入訊息閃現功能。首先,在方法前加上app.secret_key = 'some_secret',如果缺少,報錯:
RuntimeError: The session is unavailable because no secret key was set. Set the secret_key on the application to something unique and secret.
對上文的上傳照片程式碼略微改動,如下:
@app.route('/up') def up(): return render_template('up.html') # 上傳檔案 @app.route('/up_photo', methods=['POST'], strict_slashes=False) def api_upload(): file_dir = os.path.join(basedir, app.config['UPLOAD_FOLDER']) if not os.path.exists(file_dir): os.makedirs(file_dir) f = request.files['photo'] if f and allowed_file(f.filename): fname = secure_filename(f.filename) print fname ext = fname.rsplit('.', 1)[1] new_filename = Pic_str().create_uuid() + '.' + ext f.save(os.path.join(file_dir, new_filename)) flash("photo upload success") return redirect(url_for('up')) #return jsonify({"success": 0, "msg": "上傳成功"}) else: return jsonify({"error": 1001, "msg": "上傳失敗"})
模板展示程式碼:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>上傳</title> </head> <body> {% with messages = get_flashed_messages() %} {% if messages %} <ul class=flashes> {% for message in messages %} <li>{{ message }}</li> {% endfor %} </ul> {% endif %} {% endwith %} <form id="form1" method="post" action="/up_photo" enctype="multipart/form-data"> <div> <input id="File1" type="file" name="photo"/> <input type="submit">提交</input> </div> </form> </body> </html>
選擇圖片,點選上傳之後,顯示如圖所示
而當我們重新整理頁面之後,閃現訊息消失。
分類閃現,當閃現一個訊息時,是可以提供一個分類的。這更符合我們實際開發中的場景,例如,當檔案上傳成功時,我們提示訊息“photo upload success”為綠色;上傳檔案失敗時,我們提示訊息“photo upload error”為紅色。
@app.route('/up_photo', methods=['POST'], strict_slashes=False)
def api_upload():
file_dir = os.path.join(basedir, app.config['UPLOAD_FOLDER'])
if not os.path.exists(file_dir):
os.makedirs(file_dir)
f = request.files['photo']
if f and allowed_file(f.filename):
fname = secure_filename(f.filename)
print fname
ext = fname.rsplit('.', 1)[1]
new_filename = Pic_str().create_uuid() + '.' + ext
f.save(os.path.join(file_dir, new_filename))
flash("photo upload success", "success")
return redirect(url_for('up'))
#return jsonify({"success": 0, "msg": "上傳成功"})
else:
flash("photo upload error", "error")
return redirect(url_for('up'))
#return jsonify({"error": 1001, "msg": "上傳失敗"})
模板展示程式碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>上傳</title>
</head>
<body>
{% with messages = get_flashed_messages(category_filter=['success'])%}
{% if messages %}
<ul>
{% for message in messages %}
<li style="color:green">{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
{% with messages = get_flashed_messages(category_filter=['error'])%}
{% if messages %}
<ul>
{% for message in messages %}
<li style="color:red">{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
<form id="form1" method="post" action="/up_photo" enctype="multipart/form-data">
<div>
<input id="File1" type="file" name="photo"/>
<input type="submit">提交</input>
</div>
</form>
</body>
</html>
這樣,上傳成功或者失敗之後,頁面提示更加符合習慣
log記錄
日誌記錄的級別(來源:https://blog.csdn.net/iszhenyu/article/details/56846551):ERROR:這個級別的日誌意味著系統中發生了非常嚴重的問題,必須有人馬上處理,比如資料庫不可用了,系統的關鍵業務流程走不下去了等等。很多人在實際開發的時候,不會去區分問題的重要程度,只要有問題就error記錄下來,其實這樣是非常不負責任的,因為對於成熟的系統,都會有一套完整的報錯機制,那這個錯誤資訊什麼時候需要發出來,很多都是依據單位時間內error日誌的數量來確定的。因此如果我們不分輕重緩急,一律error對待,就會徒增報錯的頻率,久而久之,我們的救火隊員對錯誤警報就不會那麼在意,這個警報也就失去了原始的意義。
WARN:發生這個級別的問題時,處理過程可以繼續,但必須要對這個問題給予額外的關注。假設我們現在有一個系統,希望使用者每一個月更換一次密碼,而到期後,如果使用者沒有更新密碼我們還要讓使用者可以繼續登入,這種情況下,我們在記錄日誌時就需要使用WARN級別了,也就是允許這種情況存在,但必須及時做跟蹤檢查。
INFO:這個級別的日誌我們用的也是比較多,它一般的使用場景是重要的業務處理已經結束,我們通過這些INFO級別的日誌資訊,可以很快的瞭解應用正在做什麼。我們以在12306上買火車票為例,對每一張票對應一個INFO資訊描述“[who] booked ticket from [where] to [where]”。
DEBUG和TRACE:我們把這兩個級別放在一起說,是應為這兩個級別的日誌是隻限於開發人員使用的,用來在開發過程中進行除錯,但是其實我們有時候很難將DEBUG和TRACE區分開來,一般情況下,我們使用DEBUG足以。
呼叫日誌記錄的示例:
app.logger.debug('A value for debugging')
app.logger.warning('A warning occurred (%d apples)', 42)
app.logger.error('An error occurred')
如,放在我們上面的程式碼中,我們希望在上傳成功之後,把這條資訊記錄一下:
app.logger.info(fname+'上傳成功了.....')
這裡包括閃現訊息那部分,如果提示訊息是中文提示編碼問題,此時需要在開始地方加上:
import sys
...
reload(sys)
sys.setdefaultencoding('utf-8')