Skip to content

Commit c3fad11

Browse files
authored
Merge pull request #215 from AnguseZhang/chore/update-get-acs-result-py
feat: add logging, URL status check, constants module, and environmen…
2 parents d37119a + b0c792b commit c3fad11

3 files changed

Lines changed: 48 additions & 14 deletions

File tree

scripts/__init__.py

Whitespace-only changes.

scripts/constant.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
JOB_DETAIL_API = 'https://openapi.test.dp.tech/openapi/v1/sandbox/job'
2+
FILE_TOKEN_API = 'https://openapi.test.dp.tech/openapi/v1/sandbox/job/file/token'

scripts/get_acs_result.py

Lines changed: 46 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,14 @@
55

66
import requests
77
from dotenv import find_dotenv, load_dotenv
8+
from toolsy.logger import init_colored_logger
9+
10+
from scripts.constant import FILE_TOKEN_API, JOB_DETAIL_API
811

912
load_dotenv(find_dotenv())
1013

14+
logger = init_colored_logger(__name__)
15+
1116

1217
def download_file(url, output_path):
1318
"""下载文件并显示进度"""
@@ -26,7 +31,15 @@ def download_file(url, output_path):
2631
progress = (downloaded_size / total_size) * 100
2732
print(f"\rDownload progress: {progress:.1f}%", end='', flush=True)
2833

29-
print() # 换行
34+
35+
def check_url_status(url):
36+
"""检查URL的HTTP状态码"""
37+
try:
38+
response = requests.head(url, timeout=10) # 使用HEAD方法,只获取头部信息
39+
return response.status_code
40+
except requests.exceptions.RequestException as e:
41+
print(f"Warning: Failed to check URL status: {e}")
42+
return None
3043

3144

3245
def main():
@@ -41,53 +54,72 @@ def main():
4154

4255
args = parser.parse_args()
4356

44-
api_url = f"https://openapi.test.dp.tech/openapi/v1/sandbox/job/{args.job_id}?accessKey={os.getenv('MATERIALS_ACCESS_KEY')}"
45-
4657
# 删除已存在的输出文件
4758
if os.path.exists(args.output):
4859
os.remove(args.output)
4960

5061
# 调用API获取job信息
51-
print(f"Fetching job information for ID: {args.job_id}")
62+
logger.info(f"Fetching job information for ID: {args.job_id}")
5263

5364
try:
54-
response = requests.get(api_url)
65+
response = requests.get(
66+
f"{JOB_DETAIL_API}/{args.job_id}?accessKey={os.getenv('MATERIALS_ACCESS_KEY')}"
67+
)
5568
response.raise_for_status()
5669
data = response.json()
5770
except requests.exceptions.RequestException as e:
58-
print(f"Error: Failed to fetch data from API: {e}")
71+
logger.error(f"Error: Failed to fetch data from API: {e}")
5972
sys.exit(1)
6073
except json.JSONDecodeError as e:
61-
print(f"Error: Failed to parse JSON response: {e}")
74+
logger.error(f"Error: Failed to parse JSON response: {e}")
6275
sys.exit(1)
6376

64-
print(f"\n{json.dumps(data, indent=2, ensure_ascii=False)}\n")
77+
logger.info(f"\n{json.dumps(data, indent=2, ensure_ascii=False)}")
6578

6679
# 解析JSON获取resultUrl
6780
if data.get('code') == 0:
6881
result_url = data.get('data', {}).get('resultUrl', '')
82+
elif data.get('code') == 6020:
83+
logger.error(f"API returned error code: {data.get('code')}")
84+
sys.exit(-1)
6985
else:
7086
result_url = ''
71-
print(f"API returned error code: {data.get('code')}")
87+
logger.error(f"API returned error code: {data.get('code')}")
7288

7389
# 获取log文件的token(可选操作)
74-
token_url = 'https://openapi.test.dp.tech/openapi/v1/sandbox/job/file/token?accessKey=7c4d4edd67284c2e9c62d8b9350baaa4'
7590
token_data = {'filePath': 'log', 'jobId': args.job_id}
7691

7792
try:
78-
token_response = requests.post(token_url, json=token_data)
93+
token_response = requests.post(
94+
f"{FILE_TOKEN_API}?accessKey={os.getenv('MATERIALS_ACCESS_KEY')}",
95+
json=token_data,
96+
)
7997
token_response.raise_for_status()
8098
token_data = token_response.json()
8199
except requests.exceptions.RequestException:
82100
pass # 忽略token获取错误,因为这不是主要功能
83101

84-
print(f"\n{json.dumps(token_data, indent=2)}\n")
102+
logger.info(f"\n{json.dumps(token_data, indent=2)}")
85103

86104
log_token = token_data.get('data', {}).get('token', '')
87105
log_path = token_data.get('data', {}).get('path', '')
88106
log_host = token_data.get('data', {}).get('host', '')
89107

90-
print(f"\nlog_path: {log_host}/api/download/{log_path}?token={log_token}\n")
108+
# 构建log文件URL并检查状态
109+
if log_host and log_path and log_token:
110+
log_url = f"{log_host}/api/download/{log_path}?token={log_token}"
111+
112+
# 检查log URL的状态
113+
status_code = check_url_status(log_url)
114+
if status_code:
115+
if status_code == 400:
116+
logger.error('Warning: Log URL returned 400 Bad Request')
117+
elif status_code == 200:
118+
logger.info(f"\nlog_url: {log_url}")
119+
else:
120+
logger.error(f"Log URL returned status code: {status_code}")
121+
else:
122+
print('\nIncomplete log information - cannot construct log URL')
91123

92124
# 下载结果文件
93125
if result_url and result_url != 'null':
@@ -108,7 +140,7 @@ def main():
108140
print(f"Error: Download failed: {e}")
109141
sys.exit(1)
110142
else:
111-
print('No resultUrl found or resultUrl is empty')
143+
logger.error('No resultUrl found or resultUrl is empty')
112144
sys.exit(1)
113145

114146

0 commit comments

Comments
 (0)