Proxy Tools

0.1.0 · maintenance · verified Wed Apr 15

The `proxy-tools` library provides a simple yet useful proxy implementation for Python, based on the Gang of Four (GoF) design pattern. It was lovingly extracted from the `werkzeug` project to be applicable outside the web context, for example, to enable `@property` like behavior on modules. The current version is 0.1.0, with its last release in 2014, suggesting a maintenance or inactive release cadence. [4, 8]

Warnings

Install

Imports

Quickstart

The `proxy-tools` library provides a `Proxy` class for general object delegation and a `module_property` decorator to enable `@property`-like behavior on modules. The quickstart demonstrates how to define a `module_property` that can dynamically return a value (e.g., a current user based on a request context) and a basic `Proxy` usage with a wrapped callable. [8]

from proxy_tools import module_property

# Example: Simulating a 'current_user' on a module
# In a real application, 'request' and 'User' would be defined elsewhere.
# For this example, we'll mock them.

class MockUser:
    def __init__(self, user_id):
        self.id = user_id
        self.name = f"User_{user_id}"

    def __repr__(self):
        return f"<MockUser id={self.id}, name='{self.name}'>"

class MockRequest:
    def __init__(self, user_id):
        self.user_id = user_id

def get_current_user_from_request(request_obj):
    # Simulate fetching user from a request context
    return MockUser.find_by_id(request_obj.user_id)

# Patch MockUser to have a find_by_id method for the example
MockUser.find_by_id = lambda uid: MockUser(uid)

# Create a mock request object for the context
mock_request = MockRequest(user_id=123)

# Define a module-level property using module_property decorator
# This assumes a mechanism to get the current request, e.g., from a thread-local storage.
# For this quickstart, we'll directly use the mock_request in a closure.

class _ModuleContext:
    current_request = None

@module_property
def current_user():
    # In a real app, you'd get the request from a global/thread-local context
    if _ModuleContext.current_request:
        return get_current_user_from_request(_ModuleContext.current_request)
    return None # Or raise an error if no request context

# Set the mock request in the context for demonstration
_ModuleContext.current_request = mock_request

# Now, access current_user as if it were a module attribute
print(f"Current user via module_property: {current_user}")

# Demonstrate Proxy class (more generic use case)
def greet_target(name):
    return f"Hello, {name}!"

class MyProxy(Proxy):
    def __init__(self, target):
        super().__init__(target)

    def __call__(self, *args, **kwargs):
        print(f"Proxying call to: {self.__wrapped__.__name__} with args: {args}, kwargs: {kwargs}")
        return super().__call__(*args, **kwargs)

my_proxy_instance = MyProxy(greet_target)
print(my_proxy_instance('World'))

view raw JSON →