#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ LeonApp API示例 - 展示如何以编程方式调用API """ import json import requests class LeonAppAPI: def __init__(self, api_base_url="http://localhost/APP Store/api.php"): """初始化API客户端""" self.api_base_url = api_base_url def make_request(self, endpoint_type, params=None): """基础API请求函数""" if params is None: params = {} # 添加API类型参数 params['t'] = endpoint_type try: response = requests.get(self.api_base_url, params=params, timeout=30) response.raise_for_status() # 抛出HTTP错误 data = response.json() if data.get('status') == 'error': print(f"API错误: {data.get('message', '未知错误')}") return None return data.get('data') except requests.exceptions.RequestException as e: print(f"请求异常: {str(e)}") return None except json.JSONDecodeError: print("无法解析响应") return None def get_all_apps(self, page=1, limit=20): """获取所有应用列表""" return self.make_request('getallapps', {'page': page, 'limit': limit}) def get_app_info(self, app_id): """获取应用详情""" return self.make_request('getappinfo', {'id': app_id}) def get_all_tags(self): """获取所有标签""" return self.make_request('getalltags') def get_tag_apps(self, tag_id, page=1, limit=20): """获取标签下的应用""" return self.make_request('gettagapp', {'id': tag_id, 'page': page, 'limit': limit}) def get_developer_apps(self, developer_id, page=1, limit=20): """获取开发者的应用""" return self.make_request('getdeveloperapp', {'id': developer_id, 'page': page, 'limit': limit}) def get_developer_info(self, developer_id): """获取开发者信息""" return self.make_request('getdeveloperinfo', {'id': developer_id}) def get_all_announcements(self, page=1, limit=20): """获取所有公告""" return self.make_request('getacc', {'page': page, 'limit': limit}) def get_count_info(self): """获取统计信息""" return self.make_request('getcount') # 示例用法 if __name__ == "__main__": # 创建API客户端实例 api = LeonAppAPI() print("LeonApp API示例\n") # 1. 获取统计信息示例 print("=== 获取统计信息 ===") count_info = api.get_count_info() if count_info: print(f"应用总数: {count_info['total_apps']}") print(f"开发者总数: {count_info['total_developers']}") print(f"标签总数: {count_info['total_tags']}") print(f"公告总数: {count_info['total_announcements']}") print(f"总下载量: {count_info['total_downloads']}") print() # 2. 获取前5个应用示例 print("=== 获取前5个应用 ===") apps = api.get_all_apps(page=1, limit=5) if apps and 'apps' in apps: for app in apps['apps']: print(f"ID: {app['id']}, 名称: {app['name']}") print() # 3. 获取第一个标签的应用示例 print("=== 获取第一个标签的应用 ===") tags = api.get_all_tags() if tags and len(tags) > 0: first_tag = tags[0] print(f"标签: {first_tag['name']} (ID: {first_tag['id']})") tag_apps = api.get_tag_apps(first_tag['id'], limit=3) if tag_apps and 'apps' in tag_apps: for app in tag_apps['apps']: print(f"- {app['name']}") else: print("该标签下暂无应用") else: print("暂无标签数据") print() # 4. 使用提示 print("=== 使用提示 ===") print("1. 你可以在自己的脚本中导入此类并使用相应的方法") print("2. 根据实际需要处理API返回的数据") print("3. 记得添加错误处理和异常捕获") print("4. 如果API地址不同,初始化时可以指定:api = LeonAppAPI('http://your-api-url/api.php')")