OCI Python SDK读取工作请求响应报TypeError如何解决
错误根因
- OCI Python SDK中
list_work_requests返回的列表元素是WorkRequestSummary类实例,而非字典结构,不能使用i["id"]的下标方式取值,需通过类属性i.id访问对应值 get_work_request接口一次仅支持传入单个工作请求ID,不可传入逗号拼接的多ID字符串- 你之前转JSON失败是因为直接对SDK类对象序列化,OCI所有SDK模型对象都自带
as_dict()方法,先调用该方法转成原生Python字典即可正常序列化
修正后代码
import oci import configparser import json from oci.work_requests import WorkRequestClient DEFAULT_CONFIG = "~/.oci/config" DEFAULT_PROFILE = "DEFAULT" config_file = "config.json" def config_file_parser(config_file): config = configparser.ConfigParser() config.read(config_file) profiles = config.sections() for config_profile in profiles: work_requests = get_work_request(file=config_file, profile_name=config_profile) get_print_details(work_requests) def get_work_request(file=DEFAULT_CONFIG, profile_name=DEFAULT_PROFILE): global oci_config, identity_client, work_request_client oci_config = oci.config.from_file(file, profile_name=profile_name) identity_client = oci.identity.IdentityClient(oci_config) core_client = oci.core.ComputeClient(oci_config) work_request_client = WorkRequestClient(oci_config) work_requests = work_request_client.list_work_requests(oci_config["compartment"]).data print("{} Work Requests found.".format(len(work_requests))) return work_requests def get_print_details(work_requests): # 循环处理每个工作请求 for wr_summary in work_requests: # 类属性方式取ID,也可以用wr_summary.as_dict()["id"]取 wr_id = wr_summary.id resp = work_request_client.get_work_request(wr_id) wr_details = resp.data print() print() print('=' * 90) print('Work Request Details: {}'.format(wr_id)) print('=' * 90) # 如果需要输出JSON格式,用如下写法 # print(json.dumps(wr_details.as_dict(), indent=2)) print(wr_details) print() if __name__ == "__main__": config_file_parser(config_file)
通用排查思路
- 遇到类对象不可下标访问的报错时,可先打印
dir(对象名)查看该对象支持的所有属性和方法,确认取值方式 - 不确定SDK接口入参要求时,可打印方法的
__doc__属性查看内置说明:比如print(work_request_client.get_work_request.__doc__) - 所有OCI SDK返回的模型对象都支持
as_dict()方法转原生字典,需要转JSON或者字典操作时优先调用该方法
内容的提问来源于stack exchange,提问作者Rebecca
相关产品推荐
相关产品推荐

