Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

新增国际化方案 #9

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 52 additions & 1 deletion python_atom_sdk/__init__.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
# -*- coding: utf-8 -*-
import os

from .bklog import BKLogger, getLogger
from .const import Status, OutputTemplateType, OutputFieldType, OutputReportType, OutputErrorType
from .input import ParseParams
from .output import SetOutput
from .const import Status, OutputTemplateType, OutputFieldType, OutputReportType, OutputErrorType

log = BKLogger()
parseParamsObj = ParseParams()
Expand Down Expand Up @@ -168,5 +169,55 @@ def get_context_by_name(context_name):
return client.get_context_by_name(context_name)


def get_language():
language = os.getenv("BK_CI_LOCALE_LANGUAGE", "zh_CN")
return language


def prepare_i18n_environment(package_name):
import os
import shutil
if not os.path.exists('i18n'):
print("The 'i18n' directory does not exist.")
return
try:
shutil.copytree('i18n', f'{package_name}/i18n', dirs_exist_ok=True)
except FileExistsError:
for root, dirs, files in os.walk('i18n'):
for file in files:
src_file = os.path.join(root, file)
dst_file = os.path.join(f'{package_name}/i18n', file)
shutil.copy2(src_file, dst_file)
else:
for root, dirs, files in os.walk('i18n'):
for file in files:
src_file = os.path.join(root, file)
dst_file = os.path.join(f'{package_name}/i18n', file)
if os.path.exists(dst_file):
os.remove(dst_file)
shutil.copy2(src_file, dst_file)


def get_message_by_locale(messageCode, error_code=None, default_msg=""):
"""
@summary:根据语言环境获取对应的描述信息
:param messageCode: task.json文件中key(消息标识)或替换描述信息占位符的参数数组
:param error_code: 插件错误码
:param default_msg: 未获取到国际化信息时返回的默认信息
:return: 描述信息
"""
from .openapi import OpenApi
client = OpenApi()
language = get_language()
project_package_name = client.get_caller_project_package_name()
return client.get_message_by_locale(
project_package_name=project_package_name,
message_code=messageCode,
language=language,
error_code=error_code,
default_msg=default_msg
)


if __name__ == "__main__":
pass
70 changes: 67 additions & 3 deletions python_atom_sdk/openapi.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
# -*- coding: utf-8 -*-
import inspect
import json
import os
import traceback
import requests
import requests_toolbelt as rt
from sys import version_info
import json

import requests
from pkg_resources import resource_filename, resource_listdir, resource_isdir

from . import setting
from .bklog import BKLogger
Expand Down Expand Up @@ -147,3 +149,65 @@ def get_context_by_name(self, context_name):
.format(context_name)
url = self.generate_url(path)
return self.do_get(url)


def get_caller_project_package_name(self):
# 获取调用栈帧
stack_frames = inspect.stack()

# 查找调用 SDK 的项目包名
for frame in stack_frames:
module_name = frame[0].f_globals['__name__']
# 如果模块名不是 SDK 包名,认为找到了调用项目的包名
if not module_name.startswith('python_atom_sdk'):
project_package_name = module_name.split('.')[0]
return project_package_name

return None

def get_message_by_locale(self, project_package_name, message_code, language, error_code, default_msg):
"""
@summary:根据语言环境获取对应的描述信息
:param message_code:消息标识
:param language:语言信息
:param error_code:错误码
:param default_msg:默认信息
:return: 描述信息
"""
try:
file_name = "message_{}.properties".format(language)
file_dir = resource_filename(project_package_name, 'i18n/' + file_name)
if not os.path.exists(file_dir):
self._log.warning("Fail to get i18nMessage, the file {} was not found".format(file_name))
return default_msg

properties = {}
with open(file_dir, 'r', encoding='utf-8') as pro_file:
for line in pro_file.readlines():
if line.find('=') > 0:
strs = line.replace('\n', '').split('=')
properties[strs[0].strip()] = strs[1]

if error_code:
if isinstance(message_code, list) and message_code:
return properties[str(error_code)].format(*message_code)
return properties[str(error_code)].format(message_code)
else:
return properties[str(message_code)]
except IndexError:
self._log.warning("Fail to get i18nMessage, [message_code] formatting failed."
" The number of list parameters does not match that of formatting parameters")
return default_msg
except UnicodeDecodeError as o:
self._log.warning("Fail to get i18nMessage, UnicodeDecodeError: {}".format(o))
return default_msg
except UnicodeError as s:
self._log.warning("Fail to get i18nMessage, UnicodeError: {}".format(s))
return default_msg
except KeyError:
self._log.warning("Fail to get i18nMessage of messageCode[{0}], KeyError: '{0}'".format(message_code))
return default_msg
except Exception as e:
self._log.warning("Fail to get i18nMessage, {}".format(e))
return default_msg

14 changes: 7 additions & 7 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,22 +11,22 @@ def parse_requirements():
"""
@summary: 获取依赖
"""
reqs = []
requirements = []
if os.path.isfile(os.path.join(BASE_DIR, "requirements.txt")):
with open(os.path.join(BASE_DIR, "requirements.txt"), 'r') as reqs:
for line in reqs.readlines():
with open(os.path.join(BASE_DIR, "requirements.txt"), 'r') as reqs_file:
for line in reqs_file.readlines():
line = line.strip()
if line:
reqs.append(line)
return reqs
requirements.append(line)
return requirements



if __name__ == "__main__":
setup(
version="1.0.0",
version="1.0.1",
name="python_atom_sdk",
description="",

cmdclass={},
packages=find_packages(),
package_data={'': ['*.txt', '*.TXT']},
Expand Down