Nasajon GCF Utilities

1.1.0 · active · verified Fri Apr 17

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.

Common errors

Warnings

Install

Imports

Quickstart

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.

import json
from nsj_gcf_utils.objects.function_context import get_current_function_context
from nsj_gcf_utils.exception import GcfException

# Simulate a Flask-like request object for local testing
# In a real GCF environment, 'request' is provided by the framework.
class MockRequest:
    def __init__(self, json_data, headers=None):
        self._json_data = json_data
        self.headers = headers if headers is not None else {}

    @property
    def json(self):
        return self._json_data

    def get_json(self):
        return self._json_data

    def get_data(self):
        return json.dumps(self._json_data).encode('utf-8')


def my_gcf_handler(request):
    try:
        # Get the current function context
        # In GCF, 'request' would be the actual Flask request object.
        context = get_current_function_context(request)

        # Access context properties (these would be populated by GCF headers)
        print(f"Request ID: {context.request_id}")
        print(f"User ID: {context.user_id}")
        print(f"Entity ID: {context.entity_id}")

        return "OK", 200
    except GcfException as e:
        print(f"Error: {e}")
        return str(e), 500
    except Exception as e:
        print(f"Unexpected error: {e}")
        return str(e), 500

# Example usage with a mock request (simulating a GCF invocation)
mock_headers = {
    'X-Request-ID': 'mock-req-123',
    'X-User-ID': 'mock-user-456',
    'X-Entity-ID': 'mock-entity-789'
}
mock_json_payload = {'data': 'some_data'}
mock_request = MockRequest(mock_json_payload, headers=mock_headers)

response, status_code = my_gcf_handler(mock_request)
print(f"\nHandler Response: {response}, Status: {status_code}")

# Example of using Firestore client (requires actual GCP setup)
try:
    # from nsj_gcf_utils.firestore import get_firestore_client
    # firestore_client = get_firestore_client()
    # print("Firestore client initialized successfully.")
    print("\nUncomment Firestore client example for actual GCP interaction.")
except Exception as e:
    print(f"Could not initialize Firestore client (expected outside GCF): {e}")

view raw JSON →