一.前言
青龙面板为用户提供了OpenApi,可以创建一个应用授予部分权限,提供给第三方工具来帮我们管理面板,这样就具有较高的安全性,而且不影响主账号的操作。
二.正文
1.创建应用
(1) 登录面板-系统设置-应用设置-创建应用,命名和选择权限,一般选环境变量即可
(2) 获取Client ID和Client Secret
2.接口开发
青龙面板OpenApi和正常Api请求基本一致,只是/api/xxx改成/open/xxx。
青龙面板OpenApi最常用的场景也就是环境变量的管理,因此针对环境变量接口使用Python语言做了一个封装类:
import requests
from json import dumps as jsonDumps
class QL:
def __init__(self, address: str, id: str, secret: str) -> None:
"""
初始化
"""
self.address = address
self.id = id
self.secret = secret
self.valid = True
self.login()
def log(self, content: str) -> None:
"""
日志
"""
print(content)
def login(self) -> None:
"""
登录
"""
url = f"{self.address}/open/auth/token?client_id={self.id}&client_secret={self.secret}"
try:
rjson = requests.get(url).json()
if(rjson['code'] == 200):
self.auth = f"{rjson['data']['token_type']} {rjson['data']['token']}"
else:
self.log(f"登录失败:{rjson['message']}")
except Exception as e:
self.valid = False
self.log(f"登录失败:{str(e)}")
def getEnvs(self) -> list:
"""
获取环境变量
"""
url = f"{self.address}/open/envs?searchValue="
headers = {"Authorization": self.auth}
try:
rjson = requests.get(url, headers=headers).json()
if(rjson['code'] == 200):
return rjson['data']
else:
self.log(f"获取环境变量失败:{rjson['message']}")
except Exception as e:
self.log(f"获取环境变量失败:{str(e)}")
def deleteEnvs(self, ids: list) -> bool:
"""
删除环境变量
"""
url = f"{self.address}/open/envs"
headers = {"Authorization": self.auth,"content-type": "application/json"}
try:
rjson = requests.delete(url, headers=headers, data=jsonDumps(ids)).json()
if(rjson['code'] == 200):
self.log(f"删除环境变量成功:{len(ids)}")
return True
else:
self.log(f"删除环境变量失败:{rjson['message']}")
return False
except Exception as e:
self.log(f"删除环境变量失败:{str(e)}")
return False
def addEnvs(self, envs: list) -> bool:
"""
新建环境变量
"""
url = f"{self.address}/open/envs"
headers = {"Authorization": self.auth,"content-type": "application/json"}
try:
rjson = requests.post(url, headers=headers, data=jsonDumps(envs)).json()
if(rjson['code'] == 200):
self.log(f"新建环境变量成功:{len(envs)}")
return True
else:
self.log(f"新建环境变量失败:{rjson['message']}")
return False
except Exception as e:
self.log(f"新建环境变量失败:{str(e)}")
return False
def updateEnv(self, env: dict) -> bool:
"""
更新环境变量
"""
url = f"{self.address}/open/envs"
headers = {"Authorization": self.auth,"content-type": "application/json"}
try:
rjson = requests.put(url, headers=headers, data=jsonDumps(env)).json()
if(rjson['code'] == 200):
self.log(f"更新环境变量成功")
return True
else:
self.log(f"更新环境变量失败:{rjson['message']}")
return False
except Exception as e:
self.log(f"更新环境变量失败:{str(e)}")
return False
if __name__ == "__main__":
address = "http://127.0.0.1:5700"
client_id = "client_id"
client_secret = "client_secret"
ql = QL(address, client_id, client_secret)
envs = ql.getEnvs()
#print(envs)
envs = [{"name":"test","value":"test"}]
result = ql.deleteEnvs(envs)
三.结语
OpenApi教程到此结束了,接下来会出一篇利用OpenApi开发线报监控系统的教程。