from
flask
import
Flask, request, jsonify
import
time
import
logging
from
win10toast
import
ToastNotifier
from
datetime
import
datetime
app
=
Flask(__name__)
logging.basicConfig(
level
=
logging.INFO,
format
=
'%(asctime)s - %(levelname)s - %(message)s'
)
logger
=
logging.getLogger(__name__)
verification_codes
=
{}
CODE_EXPIRE_TIME
=
300
toaster
=
ToastNotifier()
def
send_notification(code, client_ip):
current_time
=
datetime.now().strftime(
"%Y-%m-%d %H:%M:%S"
)
message
=
f
'验证码: {code}\n来源IP: {client_ip}\n接收时间: {current_time}\n有效期: {CODE_EXPIRE_TIME}秒'
try
:
toaster.show_toast(
"验证码提醒"
,
message,
duration
=
10
,
threaded
=
True
)
except
Exception as e:
logger.error(f
"发送通知失败: {str(e)}"
)
@app
.route(
'/api/code'
, methods
=
[
'POST'
])
def
receive_code():
data
=
request.json
if
not
data
or
'code'
not
in
data:
return
jsonify({
'status'
:
'error'
,
'message'
:
'Invalid request'
}),
400
code_data
=
{
'code'
: data[
'code'
],
'timestamp'
:
int
(time.time())
}
client_ip
=
request.remote_addr
verification_codes[client_ip]
=
code_data
current_time
=
int
(time.time())
expired_keys
=
[ip
for
ip, data
in
verification_codes.items()
if
current_time
-
data[
'timestamp'
] > CODE_EXPIRE_TIME]
for
ip
in
expired_keys:
del
verification_codes[ip]
logger.info(f
"收到验证码 - 来源IP: {client_ip}, 验证码: {data['code']}"
)
send_notification(data[
'code'
], client_ip)
return
jsonify({
'status'
:
'success'
})
@app
.route(
'/api/codes'
, methods
=
[
'GET'
])
def
get_codes():
current_time
=
int
(time.time())
valid_codes
=
[data
for
data
in
verification_codes.values()
if
current_time
-
data[
'timestamp'
] <
=
CODE_EXPIRE_TIME]
return
jsonify({
'codes'
: valid_codes})
if
__name__
=
=
'__main__'
:
app.run(host
=
'0.0.0.0'
, port
=
5000
)