自定义信号
1、app.py
from flask import Flask, render_template, request, g
from utils import login_success
from blinker import Namespace
from datetime import datetime
app = Flask(__name__)
login = Namespace()
login_signal = login.signal('login')
def login_func(sender):
login_time = datetime.now()
login_ip = request.remote_addr
login_log = f'用户名:{g.username} 登录时间:{login_time} 登录IP:{login_ip}\n'
with open('login_log.txt', 'a', encoding='utf-8') as login_file:
login_file.write(login_log)
login_signal.connect(login_func)
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'GET':
return render_template('index.html')
else:
username = request.form.get('username')
password = request.form.get('password')
if username == 'admin' and password == '123456':
g.username = username
login_signal.send()
return login_success()
else:
return '用户名或密码错误'
if __name__ == '__main__':
app.run()
2、utils.py
from flask import g
def login_success():
return f'{g.username} 登录成功'
3、index.html
<form action="" method="post" enctype="multipart/form-data">
<table>
<tbody>
<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>
</tbody>
</table>
</form>
4、login_log.txt
用户名:admin 登录时间:2022-03-16 00:11:46.243264 登录IP:127.0.0.1
用户名:admin 登录时间:2022-03-16 00:11:47.315820 登录IP:127.0.0.1
用户名:admin 登录时间:2022-03-16 00:12:48.757076 登录IP:127.0.0.1