Skip to content

Commit

Permalink
[refactoring]: change name 'Context' to 'HandlerContext'
Browse files Browse the repository at this point in the history
  • Loading branch information
GLEF1X committed Dec 20, 2022
1 parent 249f20b commit 673cc2e
Show file tree
Hide file tree
Showing 8 changed files with 38 additions and 37 deletions.
8 changes: 4 additions & 4 deletions docs/code/polling/events.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,24 @@
from glQiwiApi import QiwiWallet
from glQiwiApi.core.event_fetching import executor
from glQiwiApi.core.event_fetching.dispatcher import QiwiDispatcher
from glQiwiApi.core.event_fetching.executor import Context
from glQiwiApi.core.event_fetching.executor import HandlerContext
from glQiwiApi.qiwi.clients.wallet.types import Transaction

qiwi_dp = QiwiDispatcher()
wallet = QiwiWallet(api_access_token='token', phone_number='+phone number')


@qiwi_dp.transaction_handler()
async def handle_transaction(t: Transaction, ctx: Context):
async def handle_transaction(t: Transaction, ctx: HandlerContext):
"""Handle transaction here"""
ctx.wallet # this way you can use QiwiWallet instance to avoid global variables


async def on_startup(ctx: Context):
async def on_startup(ctx: HandlerContext):
ctx.wallet # do something here


async def on_shutdown(ctx: Context):
async def on_shutdown(ctx: HandlerContext):
pass


Expand Down
6 changes: 3 additions & 3 deletions docs/code/polling/qiwi.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from glQiwiApi import QiwiWallet
from glQiwiApi.core.event_fetching import executor
from glQiwiApi.core.event_fetching.dispatcher import QiwiDispatcher
from glQiwiApi.core.event_fetching.executor import Context
from glQiwiApi.core.event_fetching.executor import HandlerContext
from glQiwiApi.core.event_fetching.filters import ExceptionFilter
from glQiwiApi.qiwi.clients.wallet.types import Transaction
from glQiwiApi.qiwi.exceptions import QiwiAPIError
Expand All @@ -11,13 +11,13 @@


@qiwi_dp.transaction_handler()
async def handle_transaction(t: Transaction, ctx: Context):
async def handle_transaction(t: Transaction, ctx: HandlerContext):
"""Handle transaction here"""
ctx.wallet # this way you can use QiwiWallet instance to avoid global variables


@qiwi_dp.exception_handler(ExceptionFilter(QiwiAPIError))
async def handle_exception(err: QiwiAPIError, ctx: Context):
async def handle_exception(err: QiwiAPIError, ctx: HandlerContext):
pass


Expand Down
4 changes: 2 additions & 2 deletions docs/code/polling/with_aiogram.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from glQiwiApi import QiwiWallet
from glQiwiApi.core.event_fetching import executor
from glQiwiApi.core.event_fetching.dispatcher import QiwiDispatcher
from glQiwiApi.core.event_fetching.executor import Context
from glQiwiApi.core.event_fetching.executor import HandlerContext
from glQiwiApi.plugins import AiogramPollingPlugin
from glQiwiApi.qiwi.clients.wallet.types import Transaction

Expand All @@ -15,7 +15,7 @@


@qiwi_dp.transaction_handler()
async def handle_transaction(t: Transaction, ctx: Context):
async def handle_transaction(t: Transaction, ctx: HandlerContext):
"""Handle transaction here"""
ctx.wallet # this way you can use QiwiWallet instance to avoid global variables

Expand Down
4 changes: 2 additions & 2 deletions docs/code/polling/with_aiogram_non_blocking.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

from glQiwiApi import QiwiWallet
from glQiwiApi.core.event_fetching.dispatcher import QiwiDispatcher
from glQiwiApi.core.event_fetching.executor import Context, start_non_blocking_qiwi_api_polling
from glQiwiApi.core.event_fetching.executor import HandlerContext, start_non_blocking_qiwi_api_polling
from glQiwiApi.qiwi.clients.wallet.types import Transaction

qiwi_dp = QiwiDispatcher()
Expand All @@ -14,7 +14,7 @@


@qiwi_dp.transaction_handler()
async def handle_transaction(t: Transaction, ctx: Context):
async def handle_transaction(t: Transaction, ctx: HandlerContext):
"""Handle transaction here"""


Expand Down
8 changes: 4 additions & 4 deletions docs/code/polling/without_globals.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from glQiwiApi import QiwiWrapper
from glQiwiApi.core.event_fetching import executor
from glQiwiApi.core.event_fetching.dispatcher import QiwiDispatcher
from glQiwiApi.core.event_fetching.executor import Context
from glQiwiApi.core.event_fetching.executor import HandlerContext
from glQiwiApi.plugins import AiogramPollingPlugin
from glQiwiApi.qiwi.clients.wallet.types import Transaction

Expand All @@ -20,16 +20,16 @@ async def aiogram_message_handler(msg: types.Message):
await msg.answer(text='袩褉懈胁械褌馃槆')


async def qiwi_transaction_handler(update: Transaction, ctx: Context):
async def qiwi_transaction_handler(update: Transaction, ctx: HandlerContext):
print(update)


def on_startup(ctx: Context) -> None:
def on_startup(ctx: HandlerContext) -> None:
logger.info('This message logged on startup')
register_handlers(ctx)


def register_handlers(ctx: Context):
def register_handlers(ctx: HandlerContext):
ctx['qiwi_dp'].transaction_handler()(qiwi_transaction_handler)
dispatcher = cast(Dispatcher, ctx['dp'])
dispatcher.register_message_handler(aiogram_message_handler)
Expand Down
4 changes: 2 additions & 2 deletions docs/code/webhooks/qiwi.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

from glQiwiApi import QiwiWallet
from glQiwiApi.core.event_fetching.dispatcher import QiwiDispatcher
from glQiwiApi.core.event_fetching.executor import Context, configure_app_for_qiwi_webhooks
from glQiwiApi.core.event_fetching.executor import HandlerContext, configure_app_for_qiwi_webhooks
from glQiwiApi.core.event_fetching.webhooks.config import (
EncryptionConfig,
HookRegistrationConfig,
Expand All @@ -21,7 +21,7 @@


@qiwi_dp.bill_handler()
async def handle_webhook(webhook: BillWebhook, ctx: Context):
async def handle_webhook(webhook: BillWebhook, ctx: HandlerContext):
# handle bill
bill = webhook.bill

Expand Down
25 changes: 13 additions & 12 deletions glQiwiApi/core/event_fetching/executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def is_awaitable(self) -> bool:
class ExecutorEvent:
def __init__(
self,
context: Context,
context: HandlerContext,
init_handlers: Iterable[Optional[_EventHandlerType]] = (),
loop: Optional[asyncio.AbstractEventLoop] = None,
) -> None:
Expand Down Expand Up @@ -94,7 +94,7 @@ def start_webhook(
on_startup: Optional[_EventHandlerType] = None,
on_shutdown: Optional[_EventHandlerType] = None,
loop: Optional[asyncio.AbstractEventLoop] = None,
context: Union[Dict[str, Any], Context, None] = None,
context: Union[Dict[str, Any], HandlerContext, None] = None,
) -> None:
"""
Blocking function that listens for webhooks.
Expand All @@ -121,7 +121,7 @@ def start_webhook(
on_shutdown=on_shutdown,
on_startup=on_startup,
loop=loop,
context=Context(context),
context=HandlerContext(context),
)
executor.start_webhook(config=webhook_config)

Expand All @@ -135,7 +135,7 @@ def start_polling(
on_startup: Optional[_EventHandlerType] = None,
on_shutdown: Optional[_EventHandlerType] = None,
loop: Optional[asyncio.AbstractEventLoop] = None,
context: Union[Dict[str, Any], Context, None] = None,
context: Union[Dict[str, Any], HandlerContext, None] = None,
) -> None:
"""
Setup for long-polling mode. Support only `glQiwiApi.types.Transaction` as event.
Expand Down Expand Up @@ -167,7 +167,7 @@ def start_polling(
on_startup=on_startup,
on_shutdown=on_shutdown,
loop=loop,
context=Context(context),
context=HandlerContext(context),
)
executor.start_polling()

Expand All @@ -180,7 +180,7 @@ async def start_non_blocking_qiwi_api_polling(
on_startup: Optional[_EventHandlerType] = None,
on_shutdown: Optional[_EventHandlerType] = None,
loop: Optional[asyncio.AbstractEventLoop] = None,
context: Union[Dict[str, Any], Context, None] = None,
context: Union[Dict[str, Any], HandlerContext, None] = None,
) -> asyncio.Task:
if context is None:
context = {}
Expand All @@ -192,7 +192,7 @@ async def start_non_blocking_qiwi_api_polling(
on_startup=on_startup,
on_shutdown=on_shutdown,
loop=loop,
context=Context(context),
context=HandlerContext(context),
)
return await executor.start_non_blocking_polling()

Expand All @@ -203,11 +203,11 @@ def configure_app_for_qiwi_webhooks(
app: web.Application,
cfg: WebhookConfig,
) -> web.Application:
executor = WebhookExecutor(wallet, dispatcher, context=Context({}))
executor = WebhookExecutor(wallet, dispatcher, context=HandlerContext({}))
return executor.add_routes_for_webhook(app, cfg)


class Context(Dict[str, Any]):
class HandlerContext(Dict[str, Any]):
def __getattr__(self, item: str) -> Any:
return self[item]

Expand All @@ -216,6 +216,7 @@ def wallet(self) -> Union[QiwiWallet, QiwiWrapper]:
return cast(Union[QiwiWallet, QiwiWrapper], self[WALLET_CTX_KEY])


# for backward compatibility
Context = HandlerContext


Expand All @@ -224,7 +225,7 @@ def __init__(
self,
dispatcher: BaseDispatcher,
*plugins: Pluggable,
context: Context,
context: HandlerContext,
loop: Optional[asyncio.AbstractEventLoop] = None,
on_startup: Optional[Callable[..., Any]] = None,
on_shutdown: Optional[Callable[..., Any]] = None,
Expand Down Expand Up @@ -290,7 +291,7 @@ def __init__(
wallet: Union[QiwiWallet, QiwiWrapper],
dispatcher: BaseDispatcher,
*plugins: Pluggable,
context: Context,
context: HandlerContext,
loop: Optional[asyncio.AbstractEventLoop] = None,
timeout: Union[float, int] = DEFAULT_TIMEOUT,
skip_updates: bool = False,
Expand Down Expand Up @@ -401,7 +402,7 @@ def __init__(
wallet: Union[QiwiWallet, QiwiWrapper],
dispatcher: BaseDispatcher,
*plugins: Pluggable,
context: Context,
context: HandlerContext,
on_startup: Optional[_EventHandlerType] = None,
on_shutdown: Optional[_EventHandlerType] = None,
loop: Optional[asyncio.AbstractEventLoop] = None,
Expand Down
16 changes: 8 additions & 8 deletions tests/unit/test_event_fetching/test_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from glQiwiApi import QiwiWallet
from glQiwiApi.core.event_fetching.dispatcher import QiwiDispatcher
from glQiwiApi.core.event_fetching.executor import (
Context,
HandlerContext,
ExecutorEvent,
start_non_blocking_qiwi_api_polling,
)
Expand All @@ -18,9 +18,9 @@

class TestExecutorEvent:
async def test_fire(self):
context = Context({'api_key': 'fake_api_key'})
context = HandlerContext({'api_key': 'fake_api_key'})

async def init_event(ctx: Context) -> NoReturn:
async def init_event(ctx: HandlerContext) -> NoReturn:
assert ctx == context
raise RuntimeError()

Expand All @@ -32,11 +32,11 @@ async def init_event(ctx: Context) -> NoReturn:
await event.fire()

async def test_fire_sync_handlers(self):
context = Context({'api_key': 'fake_api_key'})
context = HandlerContext({'api_key': 'fake_api_key'})

event = ExecutorEvent(context)

def on_event(ctx: Context) -> NoReturn:
def on_event(ctx: HandlerContext) -> NoReturn:
assert ctx == context
raise RuntimeError()

Expand Down Expand Up @@ -65,20 +65,20 @@ async def history(


async def test_start_non_blocking_qiwi_api_polling(transaction: Transaction) -> None:
c = Context({'api_key': 'my_api_key'})
c = HandlerContext({'api_key': 'my_api_key'})
wallet = WalletStub(transaction)
dp = QiwiDispatcher()

handled_transaction_event = asyncio.Event()
handle_on_startup = asyncio.Event()

@dp.transaction_handler()
async def handle_transaction(txn: Transaction, ctx: Context):
async def handle_transaction(txn: Transaction, ctx: HandlerContext):
assert ctx['api_key'] == 'my_api_key'
assert ctx.wallet == wallet
handled_transaction_event.set()

async def on_startup(ctx: Context):
async def on_startup(ctx: HandlerContext):
assert ctx['api_key'] == 'my_api_key'
assert ctx.wallet == wallet
handle_on_startup.set()
Expand Down

0 comments on commit 673cc2e

Please sign in to comment.