为Google Analytics Reporting API设置HTTPproxy

2024-10-03 04:40:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经阅读了以下链接,这些链接告诉我们如何在Google API上设置代理:

我的问题与其他问题不同,因为我使用的是来自oauth2client.service_account包的ServiceAccountCredentials方法。API密钥的身份验证是通过json文件完成的。(也是ServiceAccountCredentials.from_json_keyfile_name方法)。每当我想请求google服务时,我都想从http代理服务器传递它,不幸的是,web上没有任何用于此目的的丰富文档(或者我可能找不到它们)

ga_base_config.yml

PROXY:
  proxy_user: '<proxy_user>'
  proxy_pass: '<proxy_password>'
  proxy_host: '<proxy_host>'
  proxy_port: <port_no>

main.py

class GA:
    def __init__(self, root_dir):
        with open(os.path.join(root_dir, 'config/ga_base_config.yml'), 'r') as yaml_file:
            try:
                self.yaml_file = yaml.safe_load(yaml_file)
                print(self.yaml_file)
            except yaml.YAMLError as exc:
                print(exc)

        self.scopes = self.yaml_file['URL']['scope']
        self.proxy_info = self.yaml_file['PROXY']

        self.key_file_location = os.path.join(root_dir, self.yaml_file['KEY_FILE'])

    def initialize_analytics_reporting(self):
        """Initializes an Analytics Reporting API V4 service object.

        Returns:
          An authorized Analytics Reporting API V4 service object.
        """
        credentials = ServiceAccountCredentials.from_json_keyfile_name(
            self.key_file_location,
            self.scopes,
        )
        proxy = httplib2shim.Http(self.proxy_info)
        credentials.authorize(http=proxy)
        analytics = build(
            'analyticsreporting',
            'v4',
            credentials=credentials,
        )
        return analytics

我已经尝试了上面的代码,但它不起作用,我不知道如何从HTTP代理传递Google Analytics API

p.S.我正在使用python 3.8


Tags: selfapiconfigjsonyamldirservicegoogle