Problem
When a Cloud Function is triggered by a Pub/Sub API, the below error is observed while the code works as expected when deploying using the console:
Traceback (most recent call last): File "/layers/google.python.pip/pip/lib/python3.9/site-packages/flask/app.py", line 2447, in wsgi_app response = self.full_dispatch_request() File "/layers/google.python.pip/pip/lib/python3.9/site-packages/flask/app.py", line 1952, in full_dispatch_request rv = self.handle_user_exception(e) File "/layers/google.python.pip/pip/lib/python3.9/site-packages/flask/app.py", line 1821, in handle_user_exception reraise(exc_type, exc_value, tb) File "/layers/google.python.pip/pip/lib/python3.9/site-packages/flask/_compat.py", line 39, in reraise raise value File "/layers/google.python.pip/pip/lib/python3.9/site-packages/flask/app.py", line 1950, in full_dispatch_request rv = self.dispatch_request() File "/layers/google.python.pip/pip/lib/python3.9/site-packages/flask/app.py", line 1936, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/layers/google.python.pip/pip/lib/python3.9/site-packages/functions_framework/__init__.py", line 152, in view_func function(data, context) TypeError: main() takes 0 positional arguments but 2 were given
Environment
- Cloud Functions
- Cloud Pub/Sub API
Solution
- Modify the main function to accept two arguments:
def main(message, context)
- If the result is the following error, remove any main calls without parameters or update the calls with two parameters, as appropriate.
Error message: main() missing 2 required positional arguments: 'data' and 'context'
Cause
The error observed indicates the main function is defined to accept 0 (zero) arguments:
def main()
As per this example, Cloud Function triggered by Pub/Sub API events get two arguments namely the Pub/Sub message and the event metadata. If the main function in the Cloud Function code does not accept two arguments, then this issue will be shown. These arguments should be accepted irrespective of whether they are used.