104 lines
3.5 KiB
Plaintext
104 lines
3.5 KiB
Plaintext
async def create_model_apikey(ns={}):
|
|
import aiohttp
|
|
|
|
if not ns.get('userid'):
|
|
ns['userid'] = await get_user()
|
|
|
|
if not ns.get('userid'):
|
|
return {
|
|
'status': False,
|
|
'msg': '未找到用户'
|
|
}
|
|
|
|
# 通过userid从user_api_keys表中查询opc_apikey
|
|
db = DBPools()
|
|
async with db.sqlorContext('kboss') as sor:
|
|
records = await sor.R('user_api_keys', {'userid': ns['userid'], 'action': 'sync'})
|
|
if not records:
|
|
return {
|
|
'status': False,
|
|
'msg': '未找到用户opc_apikey'
|
|
}
|
|
|
|
already_sync_user_key = records[0]['opc_apikey']
|
|
already_sync_user_appid = records[0]['appid']
|
|
|
|
# domain 从数据库params表中获取到pname=cntoai_domain的pvalue值
|
|
db = DBPools()
|
|
async with db.sqlorContext('kboss') as sor:
|
|
domain = await sor.R('params', {'pname': 'cntoai_domain'})
|
|
if domain:
|
|
domain = domain[0]['pvalue']
|
|
else:
|
|
debug(f"create_model_apikey未找到域名")
|
|
return {
|
|
'status': False,
|
|
'msg': '未找到域名'
|
|
}
|
|
|
|
# 目标URL
|
|
url = f"{domain}/dapi/apply_apikey.dspy"
|
|
|
|
# 请求头
|
|
headers = {
|
|
"Content-Type": "application/json",
|
|
"Authorization": "Bearer %s" % already_sync_user_key
|
|
}
|
|
|
|
# 请求体数据
|
|
payload = {
|
|
"appname": ns.get('appname'),
|
|
"description": ns.get('description'),
|
|
}
|
|
|
|
# 正常返回的是 {'status': 'ok', 'data': {'id': 'HlEQmcbCA1dX0qjhffA_K', 'name': 'cn_ai_user', 'description': '', 'secretkey': 'QUZVcXg5V1p1STMybG5Ia4r9NHBpkeRw558aATmohvZ7GYptvg==', 'allowedips': None, 'orgid': 'KHtWKY2LENTU4hYYim1Ks'}}
|
|
try:
|
|
# 创建一个异步会话
|
|
result_sysnc = None
|
|
async with aiohttp.ClientSession() as session:
|
|
# 发送POST请求
|
|
async with session.post(url, headers=headers, data=json.dumps(payload)) as response:
|
|
# 打印响应状态码
|
|
debug(f"create_model_apikey状态码: {response.status}")
|
|
debug(f"create_model_apikey响应: {await response.text()}")
|
|
result_sysnc = await response.json()
|
|
|
|
if not result_sysnc.get('status') == 'ok':
|
|
debug(f"create_model_apikey创建模型apikey失败: {result_sysnc}")
|
|
return {
|
|
'status': False,
|
|
'msg': f"创建模型apikey失败: {result_sysnc}"
|
|
}
|
|
|
|
db = DBPools()
|
|
async with db.sqlorContext('kboss') as sor:
|
|
# user_api_keys表格 userid/opc_apikey
|
|
# 首先判断apikey是否存在
|
|
remote_table_id = result_sysnc['data'].get('id')
|
|
name = result_sysnc['data'].get('name')
|
|
secretkey = result_sysnc['data'].get('secretkey')
|
|
apikey = result_sysnc['data'].get('apikey')
|
|
|
|
await sor.C('user_api_keys', {
|
|
'userid': ns['userid'],
|
|
'remote_table_id': remote_table_id,
|
|
'name': name,
|
|
'opc_apikey': apikey,
|
|
'secretkey': secretkey,
|
|
'action': 'user_self_create',
|
|
})
|
|
return {
|
|
'status': True,
|
|
'msg': '创建模型apikey成功'
|
|
}
|
|
|
|
except Exception as e:
|
|
debug(f"sync_cn_ai_user{userid}同步用户失败: {e}")
|
|
return {
|
|
'status': False,
|
|
'msg': f"sync_cn_ai_user{userid}同步用户失败: {e}"
|
|
}
|
|
|
|
|
|
ret = await create_model_apikey(params_kw)
|
|
return ret |