python-web框架Flask-(七)全局對象g

g英文:global

專門用來保存用戶數據,g對象在一次請求中,當前項目所有文件中都可以使用到;但是第二次請求時,g對象會被重新創建。。。

使用g對象需要先引入該模塊:

from flask import Flask,g,render_template,request

用法:

g.xxx = xxx # 前邊是爲key 後邊是值

來個小demo:需求是,當用戶登錄時,打印用戶賬號、密碼和登陸時間:

<!-- html代碼 -->
<form action="http://localhost:5000/login" method="post">
   <input type="text" name='username' placeholder="請輸入賬號">
   <input type="password" name='password' placeholder="密碼">
   <input type="submit" value='登錄'>
</form>
from flask import Flask,g,render_template,request
from readlog import read # 引入打印用戶信息模塊(文件)
# 渲染頁面
@app.route('/')
def fn():
    return render_template('html.html')

#登錄,把用戶信息存到 g 對象
@app.route('/login',methods=['GET','POST'])
def login():
    if request.method == 'POST':
        g.username = request.form.get('username')
        g.password = request.form.get('password')
        read()
    return '登陸成功'
if __name__ == '__main__':
    app.run(debug=True)
#readlog文件-----打印用戶,用戶的密碼,什麼是時間登錄 (日誌)
from flask import g
from datetime import datetime
def read():
    now = datetime.now()
    print('登陸時間是:%s' % str(now)) # 登陸時間是:2019-09-05 15:08:32.457721
    print('用戶賬號是:%s,密碼是:%s ' % (g.username,g.password)) # 用戶賬號是:123,密碼是:lxc 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章