Skip to main content

ProxyCTX is a utility library for global context inspired by Flask, leveraging contextvars

Project description

PyPI CI pre-commit.ci status codecov PyPI - Downloads PyPI - Python Version

proxyctx

ProxyCTX is a handy utility library that empowers developers to establish a global context accessible from anywhere within their application. Its creation was inspired by Flask, a popular web framework. Under the hood, ProxyCTX leverages the Python standard module contextvars.

The library consists of just two key components:

  • Proxy: Inspired by Werkzeug's LocalProxy class (werkzeug.local)
  • Context: Inspired by Flask's AppContext class (flask.ctx)

Flask Example

In Flask, when defining a route, the corresponding method does not receive any parameters representing the incoming request. Instead, you can import a global variable called request, which conveniently holds information about the incoming request. Here's an example code snippet illustrating this:

from flask import Flask, request

app = Flask(__name__)

@app.route("/")
def index():
    print(request.method)

It's worth noting that request is not the only global variable available in Flask. You can explore the flask.globals module, which encompasses all the global variables provided by Flask.

Usage

To install the library use the following command:

pip install proxyctx

Proxy

from contextvars import ContextVar
from proxyctx import Proxy

class Greet:
    def __init__(self, message: str = None):
        self.message = message

    def greet(self, name: str):
        if self.message is None:
            print(f"Hello {name} !")
        else:
            print(f"Hello {name}, {self.message}")

ctx: ContextVar["Greet"] = ContextVar("ctx")
current_greet: "Greet" = Proxy(ctx)
current_message: str = Proxy(ctx, lambda obj: obj.message)

ctx.set(Greet("how are you ?"))
print(current_message) # "how are you ?"
current_greet.greet("Lucino772") # "Hello Lucino772, how are you ?"

ctx.set(Greet("have a nice day !"))
print(current_message) # "have a nice day !"
current_greet.greet("Lucino772") # "Hello Lucino772, have a nice day !"

Context

from contextvars import ContextVar
from proxyctx import Proxy, Context

ctx: ContextVar["GreetContext"] = ContextVar("ctx")
current_greet: "Greet" = Proxy(ctx, lambda obj: obj.greet)

class Greet:
    def __init__(self, message: str = None):
        self.message = message

    def greet(self, name: str):
        if self.message is None:
            print(f"Hello {name} !")
        else:
            print(f"Hello {name}, {self.message}")

    def greet_context(self):
        return GreetContext(self)

class GreetContext(Context):
    def __init__(self, greet: "Greet"):
        super().__init__(ctx)
        self.greet = greet

with Greet("how are you ?").greet_context():
    current_greet.greet("Lucino772") # "Hello Lucino772, how are you ?"
    with Greet("have a nice day !").greet_context():
        current_greet.greet("Lucino772") # "Hello Lucino772, have a nice day !"
    current_greet.greet("Lucino772") # "Hello Lucino772, how are you ?"

Licence

This project uses a MIT Licence view

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

proxyctx-0.1.1.tar.gz (19.3 kB view hashes)

Uploaded Source

Built Distribution

proxyctx-0.1.1-py3-none-any.whl (6.7 kB view hashes)

Uploaded Python 3

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