Giter VIP home page Giter VIP logo

proxyctx's Introduction

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

proxyctx's People

Contributors

dependabot[bot] avatar pre-commit-ci[bot] avatar lucino772 avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.