{"id":9989,"library":"nsj-gcf-utils","title":"Nasajon GCF Utilities","description":"nsj-gcf-utils (v1.1.0) is a Python library providing utilities for building Google Cloud Functions, primarily designed for applications leveraging Django and Django REST Framework. It offers tools for handling function context, interacting with Google Cloud services like Firestore, Storage, and Secret Manager, and managing tasks. The library is actively maintained with a focus on specific enterprise use cases rather than general-purpose GCF development, and updates are released as needed.","status":"active","version":"1.1.0","language":"en","source_language":"en","source_url":"https://github.com/Nasajon/nsj_gcf_utils","tags":["google-cloud-functions","gcf","django","djangorestframework","cloud","utilities"],"install":[{"cmd":"pip install nsj-gcf-utils","lang":"bash","label":"Install stable version"}],"dependencies":[{"reason":"Required for core functionality, as the library integrates heavily with Django/DRF applications deployed to GCF.","package":"Django"},{"reason":"Essential for handling API requests and responses within a Django/DRF context in GCF.","package":"djangorestframework"},{"reason":"For interacting with Google Cloud Storage services.","package":"google-cloud-storage"},{"reason":"For interacting with Google Cloud Tasks services.","package":"google-cloud-tasks"},{"reason":"For accessing secrets managed by Google Cloud Secret Manager.","package":"google-cloud-secret-manager"},{"reason":"A core dependency for secure operations, often pulled in by other Google Cloud client libraries.","package":"cryptography"}],"imports":[{"symbol":"get_current_function_context","correct":"from nsj_gcf_utils.objects.function_context import get_current_function_context"},{"note":"This is the class returned by `get_current_function_context`, useful for type hinting.","symbol":"FunctionContext","correct":"from nsj_gcf_utils.objects.function_context import FunctionContext"},{"symbol":"get_firestore_client","correct":"from nsj_gcf_utils.firestore import get_firestore_client"},{"symbol":"GcfException","correct":"from nsj_gcf_utils.exception import GcfException"}],"quickstart":{"code":"import json\nfrom nsj_gcf_utils.objects.function_context import get_current_function_context\nfrom nsj_gcf_utils.exception import GcfException\n\n# Simulate a Flask-like request object for local testing\n# In a real GCF environment, 'request' is provided by the framework.\nclass MockRequest:\n    def __init__(self, json_data, headers=None):\n        self._json_data = json_data\n        self.headers = headers if headers is not None else {}\n\n    @property\n    def json(self):\n        return self._json_data\n\n    def get_json(self):\n        return self._json_data\n\n    def get_data(self):\n        return json.dumps(self._json_data).encode('utf-8')\n\n\ndef my_gcf_handler(request):\n    try:\n        # Get the current function context\n        # In GCF, 'request' would be the actual Flask request object.\n        context = get_current_function_context(request)\n\n        # Access context properties (these would be populated by GCF headers)\n        print(f\"Request ID: {context.request_id}\")\n        print(f\"User ID: {context.user_id}\")\n        print(f\"Entity ID: {context.entity_id}\")\n\n        return \"OK\", 200\n    except GcfException as e:\n        print(f\"Error: {e}\")\n        return str(e), 500\n    except Exception as e:\n        print(f\"Unexpected error: {e}\")\n        return str(e), 500\n\n# Example usage with a mock request (simulating a GCF invocation)\nmock_headers = {\n    'X-Request-ID': 'mock-req-123',\n    'X-User-ID': 'mock-user-456',\n    'X-Entity-ID': 'mock-entity-789'\n}\nmock_json_payload = {'data': 'some_data'}\nmock_request = MockRequest(mock_json_payload, headers=mock_headers)\n\nresponse, status_code = my_gcf_handler(mock_request)\nprint(f\"\\nHandler Response: {response}, Status: {status_code}\")\n\n# Example of using Firestore client (requires actual GCP setup)\ntry:\n    # from nsj_gcf_utils.firestore import get_firestore_client\n    # firestore_client = get_firestore_client()\n    # print(\"Firestore client initialized successfully.\")\n    print(\"\\nUncomment Firestore client example for actual GCP interaction.\")\nexcept Exception as e:\n    print(f\"Could not initialize Firestore client (expected outside GCF): {e}\")","lang":"python","description":"This quickstart demonstrates how to retrieve the current function context within a GCF handler. It uses `get_current_function_context` to access request-specific metadata, such as request ID, user ID, and entity ID, which are typically passed via HTTP headers in a Google Cloud Function environment. A mock request object is included to make the example runnable locally, simulating a GCF invocation. Note that Google Cloud service clients (like Firestore) require proper GCP authentication and project setup to function."},"warnings":[{"fix":"Ensure your GCF project includes Django and Django REST Framework in its `requirements.txt` if using this library. Reconsider if `nsj-gcf-utils` is the right tool for pure Python/minimalist GCFs without a Django/DRF backend.","message":"This library is not a general-purpose Google Cloud Functions utility. It has strong dependencies on Django and Django REST Framework, implying it's intended for specific architectural patterns where a Django/DRF application is deployed as a GCF. Attempting to use it in a pure, minimalist GCF environment without these frameworks will likely lead to `ModuleNotFoundError` or unexpected behavior.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Verify that the Google Cloud Function's service account has the necessary IAM roles and permissions (e.g., `roles/datastore.user` for Firestore, `roles/storage.objectViewer` for Storage) for the resources it attempts to access.","message":"Google Cloud service clients (e.g., Firestore, Storage, Secret Manager) initialized by this library will rely on the default Google Cloud authentication mechanism, typically the GCF's associated service account. Incorrect IAM permissions for this service account will lead to `PermissionDenied` errors.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Ensure that upstream callers (e.g., API Gateway, other services) are correctly populating these headers. For local testing, mock the `request` object with appropriate headers, as shown in the quickstart.","message":"The `FunctionContext` object populated by `get_current_function_context` relies on specific HTTP headers (e.g., `X-Request-ID`, `X-User-ID`, `X-Entity-ID`) being present in the incoming GCF request. If these headers are missing or not propagated, context properties might be `None` or raise `AttributeError`.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-17T00:00:00.000Z","next_check":"2026-07-16T00:00:00.000Z","problems":[{"fix":"Install the required dependencies: `pip install nsj-gcf-utils Django djangorestframework django-cors-headers` or ensure they are listed in your `requirements.txt`.","cause":"The `nsj-gcf-utils` library has hard dependencies on Django and Django REST Framework, but these packages were not installed in the environment.","error":"ModuleNotFoundError: No module named 'django'"},{"fix":"Grant the appropriate IAM roles to the GCF's service account. For example, if accessing Firestore, add `Cloud Datastore User` (roles/datastore.user) or `Cloud Datastore Editor` (roles/datastore.editor).","cause":"The Google Cloud Function's service account does not have the necessary IAM permissions to access the Google Cloud resource (e.g., Firestore database, Cloud Storage bucket, Secret Manager secret) that the library is trying to use.","error":"google.api_core.exceptions.PermissionDenied: 7 PERMISSION_DENIED: User lacks permission"},{"fix":"Ensure that the HTTP request object passed to your GCF handler contains the necessary headers (`X-Request-ID`, `X-User-ID`, `X-Entity-ID`, etc.) which `nsj-gcf-utils` expects to populate the context. For local testing, pass a mock request with these headers.","cause":"This typically occurs when `get_current_function_context()` is called, but the underlying Flask `request` object (or its mock) does not contain the expected headers (like `X-Request-ID`), causing `FunctionContext` properties to remain `None`.","error":"AttributeError: 'NoneType' object has no attribute 'request_id'"}]}