Skip to content

Commit

Permalink
🔥Refactor before release 1.0beta
Browse files Browse the repository at this point in the history
  • Loading branch information
GLEF1X committed Jun 5, 2021
1 parent d894923 commit 71f1bc7
Show file tree
Hide file tree
Showing 24 changed files with 354 additions and 296 deletions.
34 changes: 17 additions & 17 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,23 +116,23 @@ from glQiwiApi import QiwiWrapper


async def main():
# You can pass on only p2p tokens, if you want to use only p2p api
async with QiwiWrapper(
secret_p2p="your_secret_p2p"
) as w:
# Таким образом можно создать p2p счет
# В примере указан счёт на 1 рубль с комментарием some_comment
bill = await w.create_p2p_bill(
amount=1,
comment='my_comm'
)
# Проверка на статус "оплачено" созданного p2p счёта
if (await w.check_p2p_bill_status(bill_id=bill.bill_id)) == 'PAID':
print('Успешно оплачено')
else:
print('Транзакция не найдена')
# Или, начиная с версии апи 0.2.0
print(await bill.paid) # This will print you bool answer
# You can pass on only p2p tokens, if you want to use only p2p api
async with QiwiWrapper(
secret_p2p="your_secret_p2p"
) as w:
# Таким образом можно создать p2p счет
# В примере указан счёт на 1 рубль с комментарием some_comment
bill = await w.create_p2p_bill(
amount=1,
comment='my_comm'
)
# Проверка на статус "оплачено" созданного p2p счёта
if (await w.check_p2p_bill_status(bill_id=bill.bill_id)) == 'PAID':
print('Успешно оплачено')
else:
print('Транзакция не найдена')
# Или, начиная с версии апи 0.2.0
print(await bill.paid) # This will print you bool answer


asyncio.run(main())
Expand Down
7 changes: 7 additions & 0 deletions SETUP_REQUIREMENTS.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
pytz>=2021.1
aiofiles>=0.6.0
aiohttp>=3.7.4post0
pydantic>=1.8.2
wheel>=0.36.2
loguru>=0.5.3

4 changes: 3 additions & 1 deletion examples/qiwi/polling.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import datetime

from glQiwiApi import QiwiWrapper, types
from glQiwiApi.utils import executor

api_access_token = "your token"
phone_number = "your number"
Expand All @@ -20,7 +21,8 @@ def on_startup(wrapper: QiwiWrapper):
wrapper.dispatcher.logger.info("This message logged on startup")


wallet.start_polling(
executor.start_polling(
wallet,
get_updates_from=datetime.datetime.now() - datetime.timedelta(hours=1),
on_startup=on_startup
)
9 changes: 2 additions & 7 deletions examples/qiwi/pretty_webhook.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import logging

from glQiwiApi import QiwiWrapper, types
from glQiwiApi.utils import executor

wallet = QiwiWrapper(
api_access_token='token from https://qiwi.com/api/',
Expand All @@ -20,8 +19,4 @@ async def fetch_bill(notification: types.Notification):

FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'

wallet.start_webhook(
port=80,
level=logging.INFO,
format=FORMAT
)
executor.start_webhook(wallet, port=80)
2 changes: 1 addition & 1 deletion glQiwiApi/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from .utils.exceptions import * # NOQA
from .yoo_money import YooMoneyAPI # NOQA

__version__ = '1.0beta'
__version__ = '1.0alpha'

__all__ = (
(
Expand Down
35 changes: 31 additions & 4 deletions glQiwiApi/core/abstracts.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
from __future__ import annotations

import abc
import asyncio
import typing
import unittest
from typing import AsyncGenerator, Optional, Dict, Any, Union, List, Tuple
from types import TracebackType
from typing import AsyncGenerator, Optional, Dict, Any, Union, List, Tuple, Type

from aiohttp import web
from aiohttp.typedefs import LooseCookies
Expand All @@ -27,7 +31,10 @@ def __call__(cls, *args, **kwargs):
return cls._instances[cls]


class BaseStorage(abc.ABC):
T = typing.TypeVar("T")


class BaseStorage(abc.ABC, typing.Generic[T]):
"""
Абстрактный класс контроллера кэша
Expand Down Expand Up @@ -97,7 +104,7 @@ class AbstractParser(abc.ABC):
""" Abstract class of parser for send request to different API's"""

@abc.abstractmethod
async def _request(
async def _make_request(
self,
url: str,
get_json: bool,
Expand All @@ -115,7 +122,9 @@ async def _request(
Dict[str, Union[str, int, List[
Union[str, int]
]]]
]) -> Response:
],
get_bytes: bool,
**kwargs) -> Response:
raise NotImplementedError

@abc.abstractmethod
Expand All @@ -128,6 +137,13 @@ async def fetch(
""" You can override it, but is must to return an AsyncGenerator """
raise NotImplementedError

@abc.abstractmethod
async def close(self) -> None: # pragma: no cover
"""
Close client session
"""
pass

def raise_exception(
self,
status_code: str,
Expand All @@ -136,6 +152,17 @@ def raise_exception(
) -> None:
"""Метод для обработки исключений и лучшего логирования"""

async def __aenter__(self) -> AbstractParser:
return self

async def __aexit__(
self,
exc_type: Optional[Type[BaseException]],
exc_value: Optional[BaseException],
traceback: Optional[TracebackType],
) -> None:
await self.close()


class BaseWebHookView(web.View):
"""
Expand Down
43 changes: 28 additions & 15 deletions glQiwiApi/core/aiohttp_custom_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,13 @@

class RequestManager(HttpXParser):
"""
Немного переделанный HttpXParser
под платежные системы и кэширование запросов
Deal with :class:`Storage`,
caching queries and managing stable work of sending requests
"""
__slots__ = (
'without_context', 'messages', '_cache', '_cached_key',
'_connector_type', '_connector_init', '_should_reset_connector',
'_proxy'
'without_context', 'messages', '_cache', '_should_reset_connector',
'_connector_type', '_connector_init', '_proxy'
)

def __init__(
Expand All @@ -33,17 +32,26 @@ def __init__(
self.without_context: bool = without_context
self.messages: Optional[Dict[str, str]] = messages
self._cache: Storage = Storage(cache_time=cache_time)
self._cached_key: str = "session"

def reset_storage(self) -> None:
def reset_cache(self) -> None:
""" Clear all cache in storage """
self._cache.clear(force=True)

async def _request(self, *args, **kwargs) -> Response:
async def make_request(self, **kwargs) -> Response:
""" The user-friendly method that allows sending requests to any URL """
return await super(RequestManager, self)._make_request(**kwargs)

async def _make_request(self, *args, **kwargs) -> Response:
""" Send request to service(API) """
# Получаем текущий кэш используя ссылку как ключ
response = self._cache[(kwargs.get('url'))]
if not self._cache.validate(kwargs):
response = await super()._request(*args, **kwargs)
try:
response = await super()._make_request(*args, **kwargs)
except aiohttp.ContentTypeError:
raise RequestError(message="Unexpected error. Cannot deserialize answer.",
status_code="unknown")

# Проверяем, не был ли запрос в кэше, если нет,
# то проверяем статус код и если он не 200 - выбрасываем ошибку
if not isinstance(response, Cached):
Expand All @@ -58,6 +66,15 @@ async def _request(self, *args, **kwargs) -> Response:

return response

async def _close_session(self):
if self.without_context:
await super(RequestManager, self).close()

async def close(self) -> None:
""" Close aiohttp session and reset cache data """
await super(RequestManager, self).close()
self.reset_cache()

def raise_exception(
self,
status_code: str,
Expand All @@ -75,10 +92,6 @@ def raise_exception(
json_info=json_info
)

async def _close_session(self):
if self.without_context and not self.session.closed:
await self.session.close()

def _cache_all(self, response: Response, kwargs: Dict[Any, Any]):
resolved: Cached = self._cache.convert_to_cache(
result=response.response_data,
Expand All @@ -89,8 +102,8 @@ def _cache_all(self, response: Response, kwargs: Dict[Any, Any]):

@property
def is_session_closed(self) -> bool:
if isinstance(self.session, aiohttp.ClientSession):
if not self.session.closed:
if isinstance(self._session, aiohttp.ClientSession):
if not self._session.closed:
return True
return False

Expand Down
Loading

0 comments on commit 71f1bc7

Please sign in to comment.