Python 3.6 Googleads TypeError: cannot use a string pattern on a bytes-like object

Python 3.6 Googleads TypeError: cannot use a string pattern on a bytes-like object

我尝试使用 Python 3.6 与 Google Adwords API 建立联系。我设法安装了这些库,得到了 developer tokenclient_customer_iduser_agentclient_idclient_secret 并成功请求了 refresh_token.

我的 googleads.yaml 文件如下所示:

adwords:
  developer_token: hta...
  client_customer_id: 235-...-....
  user_agent: mycompany
  client_id: 25785...apps.googleusercontent.com
  client_secret: J9Da...
  refresh_token: 1/ckhGH6...

当 运行 第一个 python 脚本 get_campaigns.py 时,我在 ...\Anaconda3\lib\site-packages\googleads-10.0.0-py3.6.egg\googleads\util.py", line 302, in filter

中得到非常通用的响应 TypeError: cannot use a string pattern on a bytes-like object

其他函数如traffic_estimator_service.get(selector) 产生同样的错误。此外,当启动 Python 脚本 get_campaigns.py 时,我收到以下警告,这可能解释了一些事情:

WARNING:googleads.common:Your default encoding, cp1252, is not UTF-8. Please run this script with UTF-8 encoding to avoid errors.
INFO:oauth2client.client:Refreshing access_token
INFO:googleads.common:Request summary - {'methodName': get, 'clientCustomerId': xxx-xxx-xxxx}

我尝试了很多方法,但仍然找不到导致错误的原因。我的设置似乎是正确的,我使用了提供的例子here。非常感谢您的帮助!

目前有两种解决方案:

一个: 使用 Python2.7,为我解决了这个错误。

两个: 对于 python 3

def method_waraper(self, record):
    def filter(self, record):
        if record.args:
            arg = record.args[0]
            if isinstance(arg, suds.transport.Request):
                new_arg = suds.transport.Request(arg.url)
                sanitized_headers = arg.headers.copy()
                if self._AUTHORIZATION_HEADER in sanitized_headers:
                    sanitized_headers[self._AUTHORIZATION_HEADER] = self._REDACTED
                new_arg.headers = sanitized_headers
                msg = arg.message
                if sys.version_info.major < 3:
                    msg = msg.decode('utf-8')
                new_arg.message = self._DEVELOPER_TOKEN_SUB.sub(
                    self._REDACTED, str(msg, encoding='utf-8'))
                record.args = (new_arg,)
    return filter(self, record)
googleads.util._SudsTransportFilter.filter = method_waraper

该方案修改了google提供的代码,增加了二进制字符串的utf编码,解决了我们的问题。