Giter Club home page Giter Club logo

simple-proxifier's Introduction

simple-proxifier

A package, used to recieve user's request, add some pre- & post-middlewares, handle this request with aiohttp and return response.

Depends only on aiohttp.

Currently middlewares are able to change Request instance, but not Response instance.

Usage example

from aiohttp import web

from proxifier import Proxifier, ProxifierMiddleware
from proxifier.types.generic import Request_T, CallNext_T

REDIRECT_URL = "/"


class LogPreMiddleware(ProxifierMiddleware):
    """Simple logging middleware"""
    async def __call__(self, request: web.Request, call_next: CallNext_T) -> Request_T:
        print(f"Handling {request.method} request to {request.url} from {request.remote}")
        return await call_next(request)


class ChangeUserRelURL(ProxifierMiddleware):
    """Changes `Request` instance `rel_url` parameter"""
    def __init__(self, rel_url: str):
        self.rel_url = rel_url
        """Final `rel_url`"""

    async def __call__(self, request: web.Request, call_next: CallNext_T) -> Request_T:
        request = request.clone(rel_url=self.rel_url)
        return await call_next(request)


async def init_app() -> web.Application:
    """Initialize the aiohttp application."""
    app = web.Application()

    _proxifier = Proxifier()  # `Proxifier` initializes with default `BasicAsyncHandler` handler
    _proxifier.add_pre_middleware(LogPreMiddleware())
    _proxifier.add_pre_middleware(ChangeUserRelURL(rel_url=REDIRECT_URL))
    _proxifier.add_pre_middleware(LogPreMiddleware())

    app['proxifier'] = _proxifier

    app.router.add_route('*', '/{tail:.*}', app['proxifier'].handle)

    return app

if __name__ == '__main__':
    web.run_app(init_app(), host='127.0.0.1', port=8080)

Installation

  • Clone git repository
git clone https://github.com/arud3nko/simple-proxifier.git
  • Install dependencies
pip install -r requirements.txt

Running tests

  • Install dependencies
pip install -r tests/requirements.txt
  • Run pytest
pytest tests

Adding middlewares

You can simply inherit class from ProxifierMiddleware and add it to Proxifier using add_pre_middleware() and add_post_middleware().

class ProxifierMiddleware(ABC):
    """Base proxifier middleware class"""

    @abstractmethod
    async def __call__(self, request: Request_T, call_next: Callable[[], Coroutine[..., Request_T, ...]]):
        """Abstract __call__ method

        :param request: `Request` instance
        :param call_next: Instance of type `Callable`"""
        pass

Adding handler

You can setup your own inherited from RequestHandler handler into Proxifier.handler property.

class RequestHandler(ABC):
    """Base request handler"""
    @abstractmethod
    async def __call__(self, request: Request_T, *args, **kwargs):
        """Handle request"""
        pass

    @property
    @abstractmethod
    def session(self) -> Session_T:
        pass

    @session.setter
    @abstractmethod
    def session(self, v: Session_T):
        pass

Authors

License

MIT

simple-proxifier's People

Contributors

arud3nko 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.