1

I have a python script from a Google API but when I run it, I get error: Cannot assign to a method on line that states:

request.get_method = lambda: method

Code block (Full code: https://cloud.google.com/identity/docs/how-to/create-devices):

def create_delegated_credentials(user_email):
  credentials = service_account.Credentials.from_service_account_file(
      SA_FILE,
      scopes=['https://www.googleapis.com/auth/cloud-identity.devices'])

  delegated_credentials = credentials.with_subject(user_email)

  return delegated_credentials

request = google.auth.transport.requests.Request()
dc = create_delegated_credentials(ADMIN_EMAIL)
dc.refresh(request)
print('Access token: ' + dc.token + '\n')

header = {...}
body = {...}

serialized_body = json.dumps(body, separators=(',', ':'))

request_url = BASE_URL + 'devices'
print('Request URL: ' + request_url)
print('Request body: ' + serialized_body)

serialized_body = json.dumps(body, separators=(',', ':'))
request = urllib.request.Request(request_url, serialized_body, headers=header)
request.get_method = lambda: 'POST'                                   ############HERE

Does anyone know how to fix this?

anthony sottile
  • 61,815
  • 15
  • 148
  • 207
elZuko
  • 13
  • 4
  • 1
    Please print the entire error message including the stack trace – juanpa.arrivillaga Apr 15 '21 at 01:55
  • `get_method` is a method defined in the standard Python `Request` class. Replacing it is extremely suspect. What do you aim to accomplish here? – Silvio Mayolo Apr 15 '21 at 02:33
  • So the full error is just "tests/__init__.py:178: error: Cannot assign to a method" I'm running this in a Docker container with mypy on it. I believe the error is from that because it works perfectly fine when I run it on my local machine. As to Silvio's point, my only goal is to have the script work as intended. The code is directly from Google's API documentation. – elZuko Apr 15 '21 at 14:07

1 Answers1

1

instead of modifying the Request object (which mypy is helpfully erroring on as generally an assignment to a function is a mistake or a monkeypatch hack) you can set the method directly in construction of Request:

request = urllib.request.Request(request_url, serialized_body, headers=header, method='POST')

this parameter was added in python3.3

anthony sottile
  • 61,815
  • 15
  • 148
  • 207