保存全局变量的g属性
g:global
- g对象是专门用来保存用户的自定义数据的
- g对象在一次请求中的所有的代码的地方,都是可以使用的
# g_demo.py
from flask import Flask,g,render_template,request
from utils 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 = 'zhiliao'
#login_log(username)
g.ip = 'xxx'
login_log()
return '恭喜!登录成功!'
else:
return '你的用户名或密码错误!'
if __name__ == '__main__':
app.run(debug=True)
# utils.py
from flask import g
# def login_log(username):
# print('当前登录的用户是:%s' %username)
def login_log():
print('当前登录的用户是:%s' % g.username)
def login_ip_log():
pass
<!--templates/login.html-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name = "username"></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name = "password"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value = "登录"></td>
</tr>
</table>
</form>
</body>
</html>
网友评论