1. What is the object g?
- In the flask, to have a special g object stores user information, the full name of g is global.
- G object where a request for all code, can all be used.
Assignment way
from flask import Flask, g, render_template, request
from ulits import login_log
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'index'
@app.route('/login/', methods=['GET', 'POST'])
def login():
if request.method == 'GET':
return render_template('login.html')
else:
username = request.form.get('username')
password = request.form.get('password')
if username == 'zhiliao' and password == '111111':
g.username = username
login_log()
return '恭喜您!登录成功'
else:
return '登录名或密码错误!'
if __name__ == '__main__':
app.run(debug=True, host='127.0.0.1', port=8081)
Called
from flask import g
def login_log():
print('登录名为: {}'.format(g.username))
The difference between the object and the session 2.g
In my opinion, the biggest difference is, the object can be cross-session request as long as the session has not failed, request a different request will get to the same session
But the object is not g, g object does not need pipe expiration time, once a request to change a target g, or a re-assignment
G then how to use objects it? Look at the code.
login.html