I have a problem with AnonymousCredentials in combination with firestore emulator. The access to firestore with a service-account.json works fine. My goal is to remove the service-account.json and use AnonymousCredentials instead. The url and port are configured as environment variable "FIRESTORE_EMULATOR_HOST". The credentials are set like this:
from google.auth.credentials import AnonymousCredentials
from google.cloud import firestore
def main():
db = firestore.Client(credentials=AnonymousCredentials())
result = db.collection('some-collection').document('some-document').get()
print(result.to_dict())
However, the code raises an DefaultCredentialsError:
Traceback (most recent call last):
File "/usr/local/lib/python3.10/runpy.py", line 196, in _run_module_as_main
return _run_code(code, main_globals, None,
File "/usr/local/lib/python3.10/runpy.py", line 86, in _run_code
exec(code, run_globals)
File "/usr/src/app/__main__.py", line 12, in <module>
main()
File "/usr/src/app/__main__.py", line 6, in main
db = firestore.Client(credentials=AnonymousCredentials())
File "/usr/local/lib/python3.10/site-packages/google/cloud/firestore_v1/client.py", line 94, in __init__
super(Client, self).__init__(
File "/usr/local/lib/python3.10/site-packages/google/cloud/firestore_v1/base_client.py", line 125, in __init__
super(BaseClient, self).__init__(
File "/usr/local/lib/python3.10/site-packages/google/cloud/client/__init__.py", line 318, in __init__
_ClientProjectMixin.__init__(self, project=project, credentials=credentials)
File "/usr/local/lib/python3.10/site-packages/google/cloud/client/__init__.py", line 266, in __init__
project = self._determine_default(project)
File "/usr/local/lib/python3.10/site-packages/google/cloud/client/__init__.py", line 285, in _determine_default
return _determine_default_project(project)
File "/usr/local/lib/python3.10/site-packages/google/cloud/_helpers/__init__.py", line 154, in _determine_default_project
_, project = google.auth.default()
File "/usr/local/lib/python3.10/site-packages/google/auth/_default.py", line 575, in default
raise exceptions.DefaultCredentialsError(_HELP_MESSAGE)
google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. For more information, please see h
ttps://cloud.google.com/docs/authentication/getting-started
I solved it with the help of the GCP support: If you set the FIRESTORE_EMULATOR_HOST, you need credentials as mentioned in the description. You also need to set a project id via the environment variable GOOGLE_CLOUD_PROJECT. The value should start with "demo-". E.g. you could set GOOGLE_CLOUD_PROJECT to "demo-firestore". Setting this environment variable solved the problem.