Posts tagged with python

pipenv install google-ads produces an error:

ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. This is likely caused by a bug in google-ads. Report this to its maintainers. ✘ Installation Failed 

This is the whole thing:

% pipenv install google-ads Creating a virtualenv for this project... Pipfile: /Users/ralf/code/test_snippets/20-12-10_google_ads/Pipfile Using /usr/local/bin/python3.9 (3.9.0) to create virtualenv... ⠦ Creating virtual environment...created virtual environment CPython3.9.0.final.0-64 in 325ms   creator CPython3Posix(dest=/Users/ralf/.local/share/virtualenvs/20-12-10_google_ads-S7vGVfKj, clear=False, global=False)   seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=/Users/ralf/Library/Application Support/virtualenv)     added seed packages: pip==20.2.4, setuptools==50.3.2, wheel==0.35.1   activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator ✔ Successfully created virtual environment!  Virtualenv location: /Users/ralf/.local/share/virtualenvs/20-12-10_google_ads-S7vGVfKj Installing google-ads... Error:  An error occurred while installing google-ads! Error text: Processing /Users/ralf/Library/Caches/pipenv/wheels/0a/09/22/d4a45ac4200d9c68a5215e554d4181b51af2c01b4f16232b5c/google_ads-8.0.0-py3-none-any.whl Collecting googleapis-common-protos<2.0.0,>=1.5.8   Using cached googleapis_common_protos-1.52.0-py2.py3-none-any.whl (100 kB) Collecting google-auth-oauthlib<1.0.0,>=0.3.0   Using cached google_auth_oauthlib-0.4.2-py2.py3-none-any.whl (18 kB) Collecting protobuf<4.0.0,>=3.13.0   Using cached protobuf-3.14.0-py2.py3-none-any.whl (173 kB) Collecting google-api-core<2.0.0,>=1.14.0   Using cached google_api_core-1.23.0-py2.py3-none-any.whl (91 kB) Processing /Users/ralf/Library/Caches/pipenv/wheels/69/60/81/5cd74b8ee068fbe9e04ca0d53148f28f5c6e2c5b177d5dd622/PyYAML-5.3.1-cp39-cp39-macosx_11_0_x86_64.whl Requirement already satisfied, skipping upgrade: setuptools>=40.3.0 in /Users/ralf/.local/share/virtualenvs/20-12-10_google_ads-S7vGVfKj/lib/python3.9/site-packages (from google-ads->-r /var/folders/nc/s6kd50kj3gdg81vhy9qwddkw0000gn/T/pipenv-p0t2erav-requirements/pipenv-xefzspt6-requirement.txt (line 1)) (50.3.2) Collecting grpcio<2.0.0,>=1.33.2   Using cached grpcio-1.34.0.tar.gz (21.0 MB)     ERROR: Command errored out with exit status 1:      command: /Users/ralf/.local/share/virtualenvs/20-12-10_google_ads-S7vGVfKj/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/nc/s6kd50kj3gdg81vhy9qwddkw0000gn/T/pip-install-woj2xbsv/grpcio/setup.py'"'"'; __file__='"'"'/private/var/folders/nc/s6kd50kj3gdg81vhy9qwddkw0000gn/T/pip-install-woj2xbsv/grpcio/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/nc/s6kd50kj3gdg81vhy9qwddkw0000gn/T/pip-pip-egg-info-d7h_fmnt          cwd: /private/var/folders/nc/s6kd50kj3gdg81vhy9qwddkw0000gn/T/pip-install-woj2xbsv/grpcio/     Complete output (9 lines):     Traceback (most recent call last):       File "<string>", line 1, in <module>       File "/private/var/folders/nc/s6kd50kj3gdg81vhy9qwddkw0000gn/T/pip-install-woj2xbsv/grpcio/setup.py", line 359, in <module>         if mac_target and (pkg_resources.parse_version(mac_target) <       File "/Users/ralf/.local/share/virtualenvs/20-12-10_google_ads-S7vGVfKj/lib/python3.9/site-packages/pkg_resources/__init__.py", line 113, in parse_version         return packaging.version.Version(v)       File "/Users/ralf/.local/share/virtualenvs/20-12-10_google_ads-S7vGVfKj/lib/python3.9/site-packages/pkg_resources/_vendor/packaging/version.py", line 275, in __init__         match = self._regex.search(version)     TypeError: expected string or bytes-like object     ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. This is likely caused by a bug in google-ads. Report this to its maintainers. ✘ Installation Failed  

I do not know much about pipenv, I am just using it – so far without any problems. Now I started from scratch and ran brew update, brew outdated and brew upgrade before.

How do I report that to its maintainers best, and what does "its" mean, Google Ads or Pipenv? Is there something else I could do?

Update:

Following tai271828's advice here are some further information about the system I am using:

  • I just updated to Mac OS 11.1 (20C69) (so it probably was 11.01 before)
  • python --version --> Python 2.7.16
  • which python --> /usr/bin/python
  • which python3 --> /usr/local/bin/python3
  • python3 --version --> Python 3.9.0
  • which pipenv --> /usr/local/bin/pipenv
  • which pip --> /usr/local/bin/pip
  • which pip3 --> /usr/local/bin/pip3

I used homebrew to install Python 3 and then pip3 install pipenv.

Update 2:

With simply pip (instead of pipenv) I first ran into the same error, but after updating pip, it worked fine. This was my input:

python3 -m venv venv source venv/bin/activate pip install --upgrade pip pip install google-ads 

Update 3:

I tried to follow tai271828's advise, to update my pip in my pipenv env prior to installing the google-ads package. These were my commands:

pipenv --rm pipenv shell pip insall --upgrade pip exit pipenv install google-ads 

The error message still looks similar:

Installing google-ads... Adding google-ads to Pipfile's [packages]... ✔ Installation Succeeded  Pipfile.lock (16c839) out of date, updating to (f55075)... Locking [dev-packages] dependencies... Locking [packages] dependencies... Building requirements... Resolving dependencies... ✘ Locking Failed!  ERROR:pip.subprocessor:Command errored out with exit status 1:  command: /Users/ralf/.local/share/virtualenvs/20-12-10_google_ads-S7vGVfKj/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/nc/s6kd50kj3gdg81vhy9qwddkw0000gn/T/pip-resolver-p0oskrkm/grpcio/setup.py'"'"'; __file__='"'"'/private/var/folders/nc/s6kd50kj3gdg81vhy9qwddkw0000gn/T/pip-resolver-p0oskrkm/grpcio/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/nc/s6kd50kj3gdg81vhy9qwddkw0000gn/T/pip-resolver-p0oskrkm/grpcio/pip-egg-info      cwd: /private/var/folders/nc/s6kd50kj3gdg81vhy9qwddkw0000gn/T/pip-resolver-p0oskrkm/grpcio/ Complete output (9 lines): Traceback (most recent call last):   File "<string>", line 1, in <module>   File "/private/var/folders/nc/s6kd50kj3gdg81vhy9qwddkw0000gn/T/pip-resolver-p0oskrkm/grpcio/setup.py", line 359, in <module>     if mac_target and (pkg_resources.parse_version(mac_target) <   File "/Users/ralf/.local/share/virtualenvs/20-12-10_google_ads-S7vGVfKj/lib/python3.9/site-packages/pkg_resources/__init__.py", line 113, in parse_version     return packaging.version.Version(v)   File "/Users/ralf/.local/share/virtualenvs/20-12-10_google_ads-S7vGVfKj/lib/python3.9/site-packages/pkg_resources/_vendor/packaging/version.py", line 275, in __init__     match = self._regex.search(version) TypeError: expected string or bytes-like object ---------------------------------------- Traceback (most recent call last):   File "/usr/local/lib/python3.9/site-packages/pipenv/resolver.py", line 764, in <module>     main()   File "/usr/local/lib/python3.9/site-packages/pipenv/resolver.py", line 758, in main     _main(parsed.pre, parsed.clear, parsed.verbose, parsed.system, parsed.write,   File "/usr/local/lib/python3.9/site-packages/pipenv/resolver.py", line 741, in _main     resolve_packages(pre, clear, verbose, system, write, requirements_dir, packages, dev)   File "/usr/local/lib/python3.9/site-packages/pipenv/resolver.py", line 702, in resolve_packages     results, resolver = resolve(   File "/usr/local/lib/python3.9/site-packages/pipenv/resolver.py", line 684, in resolve     return resolve_deps(   File "/usr/local/lib/python3.9/site-packages/pipenv/utils.py", line 1395, in resolve_deps     results, hashes, markers_lookup, resolver, skipped = actually_resolve_deps(   File "/usr/local/lib/python3.9/site-packages/pipenv/utils.py", line 1108, in actually_resolve_deps     resolver.resolve()   File "/usr/local/lib/python3.9/site-packages/pipenv/utils.py", line 823, in resolve     results = self.resolver.resolve(max_rounds=environments.PIPENV_MAX_ROUNDS)   File "/usr/local/lib/python3.9/site-packages/pipenv/patched/piptools/resolver.py", line 180, in resolve     has_changed, best_matches = self._resolve_one_round()   File "/usr/local/lib/python3.9/site-packages/pipenv/patched/piptools/resolver.py", line 268, in _resolve_one_round     their_constraints.extend(self._iter_dependencies(best_match))   File "/usr/local/lib/python3.9/site-packages/pipenv/patched/piptools/resolver.py", line 383, in _iter_dependencies     dependencies = self.repository.get_dependencies(ireq)   File "/usr/local/lib/python3.9/site-packages/pipenv/patched/piptools/repositories/pypi.py", line 229, in get_dependencies     legacy_results = self.get_legacy_dependencies(ireq)   File "/usr/local/lib/python3.9/site-packages/pipenv/patched/piptools/repositories/pypi.py", line 350, in get_legacy_dependencies     results, ireq = self.resolve_reqs(   File "/usr/local/lib/python3.9/site-packages/pipenv/patched/piptools/repositories/pypi.py", line 306, in resolve_reqs     results = resolver._resolve_one(reqset, ireq)   File "/usr/local/lib/python3.9/site-packages/pipenv/patched/notpip/_internal/legacy_resolve.py", line 339, in _resolve_one     abstract_dist = self._get_abstract_dist_for(req_to_install)   File "/usr/local/lib/python3.9/site-packages/pipenv/patched/notpip/_internal/legacy_resolve.py", line 287, in _get_abstract_dist_for     abstract_dist = self.preparer.prepare_linked_requirement(req)   File "/usr/local/lib/python3.9/site-packages/pipenv/patched/notpip/_internal/operations/prepare.py", line 508, in prepare_linked_requirement     abstract_dist = _get_prepared_distribution(   File "/usr/local/lib/python3.9/site-packages/pipenv/patched/notpip/_internal/operations/prepare.py", line 95, in _get_prepared_distribution     abstract_dist.prepare_distribution_metadata(finder, build_isolation)   File "/usr/local/lib/python3.9/site-packages/pipenv/patched/notpip/_internal/distributions/sdist.py", line 40, in prepare_distribution_metadata     self.req.prepare_metadata()   File "/usr/local/lib/python3.9/site-packages/pipenv/patched/notpip/_internal/req/req_install.py", line 564, in prepare_metadata     self.metadata_directory = self._generate_metadata()   File "/usr/local/lib/python3.9/site-packages/pipenv/patched/notpip/_internal/req/req_install.py", line 538, in _generate_metadata     return generate_metadata_legacy(   File "/usr/local/lib/python3.9/site-packages/pipenv/patched/notpip/_internal/operations/build/metadata_legacy.py", line 115, in generate_metadata     call_subprocess(   File "/usr/local/lib/python3.9/site-packages/pipenv/patched/notpip/_internal/utils/subprocess.py", line 242, in call_subprocess     raise InstallationError(exc_msg) pipenv.patched.notpip._internal.exceptions.InstallationError: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

By the way: I upgraded to Python 3.9.1 meanwhile.

Try running the example get_campaign.py in the google ads api. The code was entered as follows

import argparse import sys from google.ads.google_ads.client import GoogleAdsClient from google.ads.google_ads.errors import GoogleAdsException def main(client, customer_id):     ga_service = client.get_service("GoogleAdsService", version="v6")     query = """         SELECT campaign.id, campaign.name         FROM campaign         ORDER BY campaign.id"""     # Issues a search request using streaming.     response = ga_service.search_stream(customer_id, query=query)     try:         for batch in response:             for row in batch.results:                 print(                     f"Campaign with ID {row.campaign.id} and name "                     f'"{row.campaign.name}" was found.'                 )     except GoogleAdsException as ex:         print(             f'Request with ID "{ex.request_id}" failed with status '             f'"{ex.error.code().name}" and includes the following errors:'         )         for error in ex.failure.errors:             print(f'\tError with message "{error.message}".')             if error.location:                 for field_path_element in error.location.field_path_elements:                     print(f"\t\tOn field: {field_path_element.field_name}")         sys.exit(1) if __name__ == "__main__":     # GoogleAdsClient will read the google-ads.yaml configuration file in the     # home directory if none is specified.     google_ads_client = GoogleAdsClient.load_from_storage('C:/Users/GoogleAPI/googleads.yaml')     parser = argparse.ArgumentParser(         description="Lists all campaigns for specified customer."     )     # The following argument(s) should be provided to run the example.     parser.add_argument(         "-c",         "--customer_id",         type=str,         required=True,         help="The Google Ads customer ID.",     )     args = parser.parse_args()     print(args.customer_id)     main(google_ads_client, args.customer_id) 

But I get this error.

 errors {   error_code {     authorization_error: USER_PERMISSION_DENIED   }   message: "User doesn\'t have permission to access customer. Note: If you\'re accessing a client customer, the manager\'s customer id must be set in the \'login-customer-id\' header. See https://developers.google.com/google-ads/api/d ocs/concepts/call-structure#login-customer-id" } 

customer id works fine for google adwords api.

If anyone knows the answer, I would appreciate it if you let me know. Thank you.

My goal is to get ACCOUNT_PERFORMANCE_REPORT with custom date range.

I've tried

oauth2_client = GoogleRefreshTokenClient(self.client_id, self.client_secret, refresh_token) adwords_client = AdWordsClient(developer_token, oauth2_client, self.user_agent) report_downloader = client.GetReportDownloader(version='v201809') report={   'reportName': 'Google xxx ACCOUNT_PERFORMANCE_REPORT',    'dateRangeType': 'CUSTOM_DATE',    'reportType': 'ACCOUNT_PERFORMANCE_REPORT',    'downloadFormat': 'CSV',    'selector':    {      'fields': ['CustomerDescriptiveName', 'Date', 'Cost'],       'dateRange': '20200501,20201031'   } } 

And got

Request Summary:  { 'clientCustomerId': 'None',  'includeZeroImpressions': 'True',  'server': 'adwords.google.com',  'skipColumnHeader': 'False',  'skipReportHeader': 'False',  'skipReportSummary': 'False',  'isError': True,  'errorMessage': '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><reportDownload Error><ApiError><type>ReportDownloadError.INVALID_REPORT_DEFINITION_XML</type><trigger>Invalid ReportDefinition Xml: DateError.INVALID_STRING_DATE @ </t rigger><fieldPath></fieldPath></ApiError></reportDownloadError>' } 

but when i use

 report= {   'reportName': 'Google xxx ACCOUNT_PERFORMANCE_REPORT',    'dateRangeType': 'LAST_7_DAYS',    'reportType': 'ACCOUNT_PERFORMANCE_REPORT',    'downloadFormat': 'CSV',    'selector':    {      'fields': ['CustomerDescriptiveName', 'Date', 'Cost']   } } 

it's ok

The question is: How to specify custom dateRange range in selector properly?

I have followed the guide below to obtain a Google Ads API refresh token for my application.

https://github.com/googleads/googleads-python-lib/wiki/API-access-on-behalf-of-your-clients-(web-flow)

Using the script below, everything worked, but the response only had an access token, while the refresh token was None.

from googleads import oauth2 import google.oauth2.credentials import google_auth_oauthlib.flow # Initialize the flow using the client ID and secret downloaded earlier. # Note: You can use the GetAPIScope helper function to retrieve the # appropriate scope for AdWords or Ad Manager. flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(     'client_secret.json',     [oauth2.GetAPIScope('adwords')]) # Indicate where the API server will redirect the user after the user completes # the authorization flow. The redirect URI is required. flow.redirect_uri = 'https://www.example.com' # Generate URL for request to Google's OAuth 2.0 server. # Use kwargs to set optional request parameters. authorization_url, state = flow.authorization_url(     # Enable offline access so that you can refresh an access token without     # re-prompting the user for permission. Recommended for web server apps.     access_type='offline',     # Enable incremental authorization. Recommended as a best practice.     include_granted_scopes='true',     # approval_prompt='force' ) print("\n" + authorization_url) print("\nVisit the above URL and grant access. You will be redirected. Get the 'code' from the query params of the redirect URL.") auth_code = input('\nCode: ').strip() flow.fetch_token(code=auth_code) credentials = flow.credentials print(credentials.__dict__) 

Before trying with the production data, I'm going to try using the Google Ads API with a test account. I have already set up that and I have the Customer ID, manager account customer ID, and the developer token. The next step in the docs states I need to set up the .yaml file which has the follwing fields:

developer_token: INSERT_DEVELOPER_TOKEN_HERE client_id: INSERT_OAUTH2_CLIENT_ID_HERE client_secret: INSERT_OAUTH2_CLIENT_SECRET_HERE refresh_token: INSERT_REFRESH_TOKEN_HERE login_customer_id: INSERT_LOGIN_CUSTOMER_ID_HERE 

My question here is what is the client_id and client_secret? I know that the refresh_token needs to set up like this in their docs: https://developers.google.com/google-ads/api/docs/client-libs/python/oauth-installed

Is the client_id and secret_id the OAuth 2.0 Client IDs setup in the my personal account in the developer console?

*I am using the Google Ads API and NOT the AdWords API