This commit is contained in:
ping 2026-03-19 16:39:07 +08:00
parent 3a318f789f
commit af954dc59a
8 changed files with 86 additions and 40 deletions

View File

@ -1,6 +1,8 @@
{ {
"baidu_sms_access_key": "您的AK", "smsConfig": {
"baidu_sms_access_key_secret": "您的SK", "baidu_sms_access_key": "ALTAKPk92fX9cgGDax83yNL8mP",
"baidu_sms_host": "sms.bj.baidubce.com", "baidu_sms_access_key_secret": "9b16b8efd4dc463d8bbd5462db1db8a5",
"baidu_sms_signature_id": "您的短信签名ID" "baidu_sms_host": "sms.bj.baidubce.com",
"baidu_sms_signature_id": "sms-sign-xQYUwp42637"
}
} }

37
models/table_create.txt Normal file
View File

@ -0,0 +1,37 @@
CREATE TABLE `sms_template` (
`id` varchar(32) NOT NULL COMMENT 'id',
`name` varchar(32) DEFAULT NULL COMMENT '模板名称',
`template_type` varchar(32) DEFAULT NULL COMMENT '模板类型',
`code` varchar(32) DEFAULT NULL COMMENT '模板编码',
`content` varchar(200) DEFAULT NULL COMMENT '模板内容',
`description` varchar(100) DEFAULT NULL COMMENT '场景说明',
`provider` varchar(100) DEFAULT NULL COMMENT '短信供应商名称',
`del_flg` varchar(1) DEFAULT '0' COMMENT '删除标志',
`create_at` timestamp NULL DEFAULT current_timestamp() COMMENT '创建时间戳',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci ROW_FORMAT=DYNAMIC COMMENT='短信模板表';
CREATE TABLE `validatecode` (
`id` varchar(32) NOT NULL COMMENT 'id',
`vcode` varchar(32) DEFAULT NULL COMMENT '验证码',
`expire_time` timestamp NOT NULL DEFAULT current_timestamp() COMMENT '有效期',
`del_flg` varchar(1) DEFAULT '0' COMMENT '删除标志',
`create_at` timestamp NOT NULL DEFAULT current_timestamp() COMMENT '创建时间戳',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci ROW_FORMAT=DYNAMIC COMMENT='验证码表';
CREATE TABLE `sms_record` (
`id` varchar(32) NOT NULL COMMENT 'id',
`customerid` varchar(32) DEFAULT NULL COMMENT '客户id',
`send_type` varchar(32) DEFAULT NULL COMMENT '发送类型',
`mobile` varchar(15) DEFAULT NULL COMMENT '手机号',
`email` varchar(32) DEFAULT NULL COMMENT '邮箱',
`message` varchar(510) DEFAULT NULL COMMENT '发送内容',
`send_time` varchar(32) DEFAULT NULL COMMENT '发送时间',
`send_status` varchar(1) DEFAULT NULL COMMENT '发送状态',
`task_status` varchar(2) DEFAULT NULL COMMENT '任务状态 1:待发送,2:待定时发送,11:发送MQ成功,12:MQ消费成功,21:请求成功,22:请求失败,31:取消发送',
`remark` varchar(200) DEFAULT NULL COMMENT '发送失败备注信息',
`del_flg` varchar(1) DEFAULT NULL COMMENT '删除标志',
`create_at` timestamp NULL DEFAULT current_timestamp() COMMENT '创建时间戳',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci ROW_FORMAT=DYNAMIC COMMENT='短信邮箱记录表';

BIN
requirements.txt Normal file

Binary file not shown.

View File

@ -19,10 +19,7 @@ import baidubce.exception as ex
from sqlor.dbpools import DBPools from sqlor.dbpools import DBPools
from appPublic.uniqueID import getID as uuid from appPublic.uniqueID import getID as uuid
from ahserver.serverenv import ServerEnv from ahserver.serverenv import ServerEnv
from sqlor.dbpools import get_sor_context
p = 'D:/Code/backend_code/test_/'
config = getConfig(p)
DBPools(config.databases)
SMS_TEMPLATE_TABLE = { SMS_TEMPLATE_TABLE = {
"summary": [{"name": "sms_template", "primary": "id"}], "summary": [{"name": "sms_template", "primary": "id"}],
@ -106,8 +103,8 @@ class SMSEngine:
return {'status': False, 'msg': str(e)} return {'status': False, 'msg': str(e)}
async def send_vcode(self, phone: str, stype: str, vcode) -> dict: async def send_vcode(self, phone: str, stype: str, vcode) -> dict:
db = DBPools() env = ServerEnv()
async with db.sqlorContext('kboss') as sor: async with get_sor_context(env, 'kboss') as sor:
template_info = await sor.R('sms_template', {'name': stype, 'del_flg': '0'}) template_info = await sor.R('sms_template', {'name': stype, 'del_flg': '0'})
if template_info: if template_info:
template_id = template_info[0]['code'] template_id = template_info[0]['code']
@ -126,8 +123,8 @@ class SMSEngine:
return await self.send(stype, template_id, phone, vcode) return await self.send(stype, template_id, phone, vcode)
async def __validation(self, stype, template_id, params, phone, resp) -> dict: async def __validation(self, stype, template_id, params, phone, resp) -> dict:
db = DBPools() env = ServerEnv()
async with db.sqlorContext('kboss') as sor: async with get_sor_context(env, 'kboss') as sor:
send_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") send_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
log = { log = {
'id': uuid(), 'id': uuid(),
@ -153,10 +150,6 @@ class SMSEngine:
code = ''.join(random.choices(string.digits, k=length)) code = ''.join(random.choices(string.digits, k=length))
code_id = uuid() code_id = uuid()
expire_time = datetime.datetime.now() + datetime.timedelta(minutes=expire_minutes) expire_time = datetime.datetime.now() + datetime.timedelta(minutes=expire_minutes)
# db = DBPools(config.databases)
# async with db.sqlorContext('kboss') as sor:
from sqlor.dbpools import get_sor_context
env = ServerEnv() env = ServerEnv()
async with get_sor_context(env, 'kboss') as sor: async with get_sor_context(env, 'kboss') as sor:
await sor.C('validatecode', { await sor.C('validatecode', {
@ -166,11 +159,11 @@ class SMSEngine:
'del_flg': '0', 'del_flg': '0',
'create_at': datetime.datetime.now() 'create_at': datetime.datetime.now()
}) })
return code_id return code_id, code
async def check_sms_code(self, code_id: str, vcode: str) -> bool: async def check_sms_code(self, code_id: str, vcode: str) -> bool:
db = DBPools() env = ServerEnv()
async with db.sqlorContext('kboss') as sor: async with get_sor_context(env, 'kboss') as sor:
code_info = await sor.R('validatecode', {'id': code_id, 'del_flg': '0'}) code_info = await sor.R('validatecode', {'id': code_id, 'del_flg': '0'})
if not code_info: if not code_info:
return False return False
@ -180,14 +173,18 @@ class SMSEngine:
return False return False
now = datetime.datetime.now() now = datetime.datetime.now()
# 处理 code_info['expire_time'] 为 datetime 对象
if isinstance(code_info['expire_time'], str):
code_info['expire_time'] = datetime.datetime.fromisoformat(code_info['expire_time'])
if now > code_info['expire_time']: if now > code_info['expire_time']:
return False return False
await sor.U('validatecode', {'id': code_id}, {'del_flg': '1'}) await sor.U('validatecode', {'id': code_id, 'del_flg': '1'})
return True return True
async def send_sms(self, phone: str, stype: str, params: dict) -> dict: async def send_sms(self, phone: str, stype: str) -> dict:
code_id = await self.generate_sms_code() code_id, code = await self.generate_sms_code()
if code_id is None: if code_id is None:
return { return {
'status': 'error', 'status': 'error',
@ -196,7 +193,7 @@ class SMSEngine:
} }
} }
vcode = {'SMSvCode': params.get('vcode', '')} vcode = {'SMSvCode': code}
result = await self.send_vcode(phone, stype, vcode) result = await self.send_vcode(phone, stype, vcode)
if result.get('status'): if result.get('status'):

7
test/pwd_encry.py Normal file
View File

@ -0,0 +1,7 @@
from appPublic.aes import aes_encode_b64
import sys
encry_key = '!@#$%^&*(*&^%$QWERTYUIqwertyui234567'
pwd = 'lima2018'
code = aes_encode_b64(encry_key, pwd)
print(code)

0
test/test_done.py Normal file
View File

View File

@ -30,7 +30,7 @@ async def get_vcode_from_db(codeid: str) -> dict:
from sqlor.dbpools import DBPools from sqlor.dbpools import DBPools
db = DBPools() db = DBPools()
async with db.sqlorContext('kboss') as sor: async with db.sqlorContext('kboss') as sor:
result = await sor.R('validatecode', {'id': codeid}) result = await sor.R('validatecode', {'id': codeid, 'del_flg': '0'})
if result: if result:
return result[0] return result[0]
return None return None
@ -200,8 +200,8 @@ async def test_send_vcode():
print("测试8: send_vcode() - 发送验证码短信") print("测试8: send_vcode() - 发送验证码短信")
print("=" * 50) print("=" * 50)
phone = "13800138000" phone = "18053191417"
stype = "注册登录验证" stype = "用户注册登录验证"
vcode = {"SMSvCode": "123456"} vcode = {"SMSvCode": "123456"}
result = await send_vcode(phone, stype, vcode) result = await send_vcode(phone, stype, vcode)
@ -226,11 +226,10 @@ async def test_send_sms():
print("测试9: send_sms() - 发送短信(整合生成和发送)") print("测试9: send_sms() - 发送短信(整合生成和发送)")
print("=" * 50) print("=" * 50)
phone = "13800138000" phone = "18053191417"
stype = "注册登录验证" stype = "用户注册登录验证"
params = {"vcode": "666666"}
result = await send_sms(phone, stype, params) result = await send_sms(phone, stype)
print(f"发送结果: {result}") print(f"发送结果: {result}")
if result.get('status') == 'error': if result.get('status') == 'error':
@ -278,22 +277,22 @@ async def main():
results = [] results = []
results.append(("get_sms_engine", await test_get_sms_engine())) # results.append(("get_sms_engine", await test_get_sms_engine()))
r, codeid = await test_generate_sms_code() # r, codeid = await test_generate_sms_code()
results.append(("generate_sms_code", r)) # results.append(("generate_sms_code", r))
r, codeid2 = await test_generate_sms_code_with_params() # r, codeid2 = await test_generate_sms_code_with_params()
results.append(("generate_sms_code(自定义参数)", r)) # results.append(("generate_sms_code(自定义参数)", r))
results.append(("check_sms_code(错误验证码)", await test_check_sms_code_wrong())) # results.append(("check_sms_code(错误验证码)", await test_check_sms_code_wrong()))
results.append(("check_sms_code(正确验证码)", await test_check_sms_code_correct())) results.append(("check_sms_code(正确验证码)", await test_check_sms_code_correct()))
results.append(("check_sms_code(无效codeid)", await test_check_sms_code_invalid_codeid())) # results.append(("check_sms_code(无效codeid)", await test_check_sms_code_invalid_codeid()))
results.append(("check_sms_code(已过期)", await test_check_sms_code_expired())) # results.append(("check_sms_code(已过期)", await test_check_sms_code_expired()))
results.append(("send_vcode", await test_send_vcode())) # results.append(("send_vcode", await test_send_vcode()))
results.append(("send_sms", await test_send_sms())) results.append(("send_sms", await test_send_sms()))
results.append(("SMSEngine属性", await test_sms_engine_attributes())) # results.append(("SMSEngine属性", await test_sms_engine_attributes()))
print("\n" + "=" * 50) print("\n" + "=" * 50)
print("测试结果汇总") print("测试结果汇总")
@ -312,6 +311,10 @@ async def main():
print("-" * 50) print("-" * 50)
print(f"总计: {passed} 通过, {failed} 失败") print(f"总计: {passed} 通过, {failed} 失败")
from ahserver.serverenv import ServerEnv
env = ServerEnv()
def get_db_name(s=None): return 'kboss'
env.get_module_dbname = get_db_name
if __name__ == '__main__': if __name__ == '__main__':
from sqlor.dbpools import DBPools from sqlor.dbpools import DBPools