Skip to main content

Provides proxy classes that allow accessing objects that are usually only accessible via function calls as objects directly.

Project description

nr.proxy

The nr.proxy module provides utilities for creating Python object proxies which will forward almost any interaction with the object to another object. This allows for the creation of very convenient APIs in Python applications (e.g. à la Flask request object).

This package requires Python 3.5 or higher.

Example: proxy

Command-line interfaces built with Click can use the Context.ensure_object() method to attach information to a context. Retrieving that information from the context include a couple of lines which over all reduce the readability of the code. Using a proxy allows you to access that information once it is initialized in the context as if the data was available globally.

import click
import nr.proxy
from pathlib import Path
from .config import Configuration

config = nr.proxy.proxy[Configuration](lambda: click.get_current_context().obj['config'])

@click.group()
@click.option('-c', '--config', 'config_file', type=Path, default='config.toml',
  default='Path to the configuration file.')
@click.pass_context
def cli(ctx: click.Context, config: Path) -> None:
  ctx.ensure_object(dict)['config'] = Configuration.load(config)

@cli.command()
def validate():
  # No need to use @click.pass_context or access ctx.obj['config'].
  config.validate()

Example: threadlocal

The below is an example for creating a globally accessible SqlAlchemy session. Inside a with-context using make_session(), the global session object can be accesses like a normal instance of the Session class. Outside of the context, accessing the session object results in a RuntimeError with the specified error message.

The advantage of this method is that the Session object does not need to be passed around, but can instead just be accessed globally.

import contextlib
import nr.proxy
from sqlalchemy.orm import sessionmaker
from typing import Generator

Session = sessionmaker()
session = nr.proxy.threadlocal[Session](
  name=__name__ + '.session',
  error_message=
    '({name}) No SqlAlchemy session is available. Ensure that you are using the '
    'make_session() context manager before accessing the global session proxy.',
)

@contextlib.contextmanager
def make_session() -> Generator[None, None, None]:
  """
  A context manager that creates a new #Session object and makes it available in the global
  #session proxy object.
  """

  nr.proxy.push(session, Session())
  try:
    yield
  except:
    session.rollback()
    raise
  else:
    session.commit()
  finally:
    nr.proxy.pop(session)

Copyright © 2020 Niklas Rosenstein

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

nr.proxy-1.0.4.tar.gz (7.4 kB view details)

Uploaded Source

Built Distribution

nr.proxy-1.0.4-py3-none-any.whl (11.9 kB view details)

Uploaded Python 3

File details

Details for the file nr.proxy-1.0.4.tar.gz.

File metadata

  • Download URL: nr.proxy-1.0.4.tar.gz
  • Upload date:
  • Size: 7.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.5.0.1 requests/2.24.0 setuptools/50.3.2 requests-toolbelt/0.9.1 tqdm/4.48.2 CPython/3.7.3

File hashes

Hashes for nr.proxy-1.0.4.tar.gz
Algorithm Hash digest
SHA256 0fbde1a85564a3a5a266befaded34bce69f6a5726c463890cd92d00aed75596d
MD5 e0803d63ce1149e9a912b4cab852f401
BLAKE2b-256 08a1ec27a4ec3c9385d638492988f67dfcd3d44e123cd791f3fec9205c1edb40

See more details on using hashes here.

File details

Details for the file nr.proxy-1.0.4-py3-none-any.whl.

File metadata

  • Download URL: nr.proxy-1.0.4-py3-none-any.whl
  • Upload date:
  • Size: 11.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.5.0.1 requests/2.24.0 setuptools/50.3.2 requests-toolbelt/0.9.1 tqdm/4.48.2 CPython/3.7.3

File hashes

Hashes for nr.proxy-1.0.4-py3-none-any.whl
Algorithm Hash digest
SHA256 842cfdc23934ec35cd10b29cbec2f0910ba618a7b5146c7db16da792ef2b2251
MD5 00ed488ff2f85e6ee0f8393f430585a0
BLAKE2b-256 829bf4f97d3b13cc3d2ad14d78b43d13a5f0410e0189b82f294bf5921f296861

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page