Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✨ Add python-iso4217 integration which eliminates Unions in currency field- #28

Open
wants to merge 2 commits into
base: dev-2.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ htmlcov

.benchmarks

glQiwiApi/t.py
glQiwiApi/playground.py.py
*.pem
# Distribution / packaging
.Python
Expand Down
5 changes: 4 additions & 1 deletion benchmarks/p2p/test_performance.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# pip install pytest-benchmark pyqiwip2p
import os
from typing import Any, Callable, Dict, Tuple

import pytest
from pyqiwip2p.AioQiwip2p import AioQiwiP2P
Expand All @@ -26,7 +27,9 @@ async def create_bill_with_pyQiwiP2P():


@pytest.fixture()
def aio_benchmark(benchmark: BenchmarkFixture) -> BenchmarkFixture:
def aio_benchmark(
benchmark: BenchmarkFixture,
) -> Callable[[Any, Tuple[Any, ...], Dict[str, Any]], None]:
import asyncio
import threading

Expand Down
2 changes: 1 addition & 1 deletion glQiwiApi/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def default_cache_storage() -> CacheStorage:
return InMemoryCacheStorage(invalidate_strategy=APIResponsesCacheInvalidationStrategy())


__version__ = '2.11'
__version__ = '2.12'

__all__ = (
# clients
Expand Down
6 changes: 3 additions & 3 deletions glQiwiApi/core/event_fetching/class_based/bill.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

from glQiwiApi.core.event_fetching.class_based.base import Handler
from glQiwiApi.qiwi.clients.p2p.types import Bill
from glQiwiApi.types.amount import PlainAmount
from glQiwiApi.types.amount import Amount

if TYPE_CHECKING:
from glQiwiApi.qiwi.clients.p2p.client import QiwiP2PClient
Expand All @@ -21,8 +21,8 @@ def bill_id(self) -> str:
return self.event.id

@property
def bill_sum(self) -> PlainAmount:
return self.event.amount
def bill_sum(self) -> Amount:
return self.event.value

@property
def pay_url(self) -> str:
Expand Down
4 changes: 2 additions & 2 deletions glQiwiApi/core/event_fetching/class_based/transaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from typing import TYPE_CHECKING, cast

from glQiwiApi.qiwi.clients.wallet.types.transaction import Transaction
from glQiwiApi.types.amount import AmountWithCurrency
from glQiwiApi.types.amount import Amount

from .base import Handler

Expand All @@ -22,5 +22,5 @@ def transaction_id(self) -> int:
return self.event.id

@property
def transaction_sum(self) -> AmountWithCurrency:
def transaction_sum(self) -> Amount:
return self.event.sum
4 changes: 2 additions & 2 deletions glQiwiApi/core/event_fetching/executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ async def start_non_blocking_qiwi_api_polling(
on_shutdown: Optional[_EventHandlerType] = None,
loop: Optional[asyncio.AbstractEventLoop] = None,
context: Union[Dict[str, Any], Context, None] = None,
) -> asyncio.Task:
) -> asyncio.Task[None]:
if context is None:
context = {}
executor = PollingExecutor(
Expand Down Expand Up @@ -312,7 +312,7 @@ def start_polling(self) -> None:
# allow graceful shutdown
pass

async def start_non_blocking_polling(self) -> asyncio.Task:
async def start_non_blocking_polling(self) -> asyncio.Task[None]:
return asyncio.create_task(self._run_infinite_polling())

async def _run_infinite_polling(self) -> None:
Expand Down
2 changes: 1 addition & 1 deletion glQiwiApi/core/event_fetching/webhooks/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@
from . import app # noqa
from .views import QiwiBillWebhookView, QiwiTransactionWebhookView

__all__ = ('QiwiBillWebhookView', 'QiwiTransactionWebhookView', 'BaseWebhookView', 'app.py')
__all__ = ('QiwiBillWebhookView', 'QiwiTransactionWebhookView', 'BaseWebhookView', 'app')
2 changes: 1 addition & 1 deletion glQiwiApi/core/session/holder.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import abc
from dataclasses import dataclass
from types import TracebackType
from typing import Any, Dict, Generic, Mapping, Optional, Set, Type, TypeVar, cast
from typing import Any, Dict, Generic, Mapping, Optional, Type, TypeVar, cast

import aiohttp
from aiohttp import ClientResponse
Expand Down
6 changes: 3 additions & 3 deletions glQiwiApi/qiwi/clients/p2p/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from glQiwiApi.qiwi.clients.p2p.methods.refund_bill import RefundBill
from glQiwiApi.qiwi.clients.p2p.methods.reject_p2p_bill import RejectP2PBill
from glQiwiApi.qiwi.clients.p2p.types import Bill, Customer, PairOfP2PKeys, RefundedBill
from glQiwiApi.types.amount import PlainAmount
from glQiwiApi.types.amount import Amount
from glQiwiApi.utils.compat import remove_suffix
from glQiwiApi.utils.deprecated import warn_deprecated
from glQiwiApi.utils.validators import String
Expand Down Expand Up @@ -105,7 +105,7 @@ async def get_bill_status(self, bill_id: str) -> str:
:param bill_id:
:return: status of bill
"""
return (await self.get_bill_by_id(bill_id)).status.value
return (await self.get_bill_by_id(bill_id)).status.amount

async def create_p2p_bill(
self,
Expand Down Expand Up @@ -175,7 +175,7 @@ async def refund_bill(
self,
bill_id: Union[str, int],
refund_id: Union[str, int],
json_bill_data: Union[PlainAmount, Dict[str, Union[str, int]]],
json_bill_data: Union[Amount, Dict[str, Union[str, int]]],
) -> RefundedBill:
"""
The method allows you to make a refund on a paid invoice.
Expand Down
2 changes: 1 addition & 1 deletion glQiwiApi/qiwi/clients/p2p/methods/create_p2p_bill.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import uuid
from datetime import datetime, timedelta
from typing import Any, ClassVar, Dict, List, Optional, Union
from typing import Any, ClassVar, Dict, List, Optional

from pydantic import Field, validator

Expand Down
6 changes: 3 additions & 3 deletions glQiwiApi/qiwi/clients/p2p/methods/refund_bill.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from glQiwiApi.core.abc.api_method import Request
from glQiwiApi.qiwi.base import QiwiAPIMethod
from glQiwiApi.qiwi.clients.p2p.types import RefundedBill
from glQiwiApi.types.amount import PlainAmount
from glQiwiApi.types.amount import Amount


class RefundBill(QiwiAPIMethod[RefundedBill]):
Expand All @@ -15,11 +15,11 @@ class RefundBill(QiwiAPIMethod[RefundedBill]):
bill_id: str = Field(..., path_runtime_value=True)
refund_id: str = Field(..., path_runtime_value=True)

json_bill_data: Union[PlainAmount, Dict[str, Union[str, int]]]
json_bill_data: Union[Amount, Dict[str, Union[str, int]]]

def build_request(self, **url_format_kw: Any) -> 'Request':
json_payload = self.json_bill_data
if isinstance(self.json_bill_data, PlainAmount):
if isinstance(self.json_bill_data, Amount):
json_payload = self.json_bill_data.json(encoder=self.Config.json_dumps) # type: ignore

return Request(
Expand Down
12 changes: 6 additions & 6 deletions glQiwiApi/qiwi/clients/p2p/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

from pydantic import BaseConfig, Extra, Field

from glQiwiApi.types.amount import HashablePlainAmount, PlainAmount
from glQiwiApi.types.amount import Amount, HashableAmount
from glQiwiApi.types.base import HashableBase
from glQiwiApi.types.exceptions import WebhookSignatureUnverifiedError

Expand Down Expand Up @@ -39,7 +39,7 @@ class BillError(HashableBase):


class Bill(HashableBase):
amount: HashablePlainAmount
amount: HashableAmount
status: BillStatus
site_id: str = Field(..., alias='siteId')
id: str = Field(..., alias='billId')
Expand All @@ -61,13 +61,13 @@ def invoice_uid(self) -> str:
class RefundedBill(HashableBase):
"""object: RefundedBill"""

amount: PlainAmount
value: Amount
datetime: datetime
refund_id: str = Field(..., alias='refundId')
status: str

def __str__(self) -> str:
return f'№{self.refund_id} {self.status} {self.amount} {self.datetime}'
return f'№{self.refund_id} {self.status} {self.value} {self.datetime}'


class BillWebhookPayload(Bill):
Expand All @@ -79,13 +79,13 @@ class BillWebhook(HashableBase):
bill: BillWebhookPayload = Field(..., alias='bill')

def __repr__(self) -> str:
return f'#{self.bill.id} {self.bill.amount} {self.bill.status} '
return f'#{self.bill.id} {self.bill.value} {self.bill.status} '

def verify_signature(self, sha256_signature: str, secret_p2p_key: str) -> None:
webhook_key = base64.b64decode(bytes(secret_p2p_key, 'utf-8'))
bill = self.bill

invoice_params = f'{bill.amount.currency}|{bill.amount.value}|{bill.id}|{bill.site_id}|{bill.status.value}'
invoice_params = f'{bill.value.currency}|{bill.value.value}|{bill.id}|{bill.site_id}|{bill.status.value}'
generated_signature = hmac.new(
webhook_key, invoice_params.encode('utf-8'), hashlib.sha256
).hexdigest()
Expand Down
6 changes: 3 additions & 3 deletions glQiwiApi/qiwi/clients/wallet/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
from glQiwiApi.qiwi.clients.wallet.methods.webhook.send_test_notification import (
SendTestWebhookNotification,
)
from glQiwiApi.types.amount import AmountWithCurrency
from glQiwiApi.types.amount import Amount
from glQiwiApi.types.arbitrary import File
from glQiwiApi.utils.validators import PhoneNumber, String

Expand Down Expand Up @@ -381,7 +381,7 @@ async def get_list_of_balances(self) -> List[Balance]:
GetBalances(), phone_number=self.phone_number_without_plus_sign
)

async def get_balance(self, *, account_number: int = 1) -> AmountWithCurrency:
async def get_balance(self, *, account_number: int = 1) -> Amount:
resp: List[Balance] = await self._request_service.execute_api_method(
GetBalances(),
phone_number=self._phone_number,
Expand Down Expand Up @@ -506,7 +506,7 @@ async def get_cross_rates(self) -> List[CrossRate]:

async def payment_by_payment_details(
self,
payment_sum: AmountWithCurrency,
payment_sum: Amount,
payment_method: PaymentMethod,
fields: PaymentDetails,
payment_id: Optional[str] = None,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Any, ClassVar, Dict, Optional
from typing import Any, ClassVar, Dict

from pydantic import Field

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from typing import ClassVar, List

from glQiwiApi.qiwi.base import QiwiAPIMethod
from glQiwiApi.qiwi.clients.wallet.types import Balance
from glQiwiApi.qiwi.clients.wallet.types.balance import AvailableBalance


Expand Down
1 change: 0 additions & 1 deletion glQiwiApi/qiwi/clients/wallet/methods/get_balances.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

from pydantic import parse_obj_as

from glQiwiApi.core.abc.api_method import ReturningType
from glQiwiApi.core.session.holder import HTTPResponse
from glQiwiApi.qiwi.base import QiwiAPIMethod
from glQiwiApi.qiwi.clients.wallet.types import Balance
Expand Down
1 change: 0 additions & 1 deletion glQiwiApi/qiwi/clients/wallet/methods/get_cross_rates.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

from pydantic import parse_obj_as

from glQiwiApi.core.abc.api_method import ReturningType
from glQiwiApi.core.session.holder import HTTPResponse
from glQiwiApi.qiwi.base import QiwiAPIMethod
from glQiwiApi.qiwi.clients.wallet.types import CrossRate
Expand Down
4 changes: 2 additions & 2 deletions glQiwiApi/qiwi/clients/wallet/methods/get_limits.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from typing import Any, ClassVar, Dict, List, Sequence
from typing import Any, ClassVar, Dict, Sequence

from glQiwiApi.core.abc.api_method import Request, ReturningType
from glQiwiApi.core.abc.api_method import Request
from glQiwiApi.core.session.holder import HTTPResponse
from glQiwiApi.qiwi.base import QiwiAPIMethod
from glQiwiApi.qiwi.clients.wallet.types import Limit
Expand Down
4 changes: 2 additions & 2 deletions glQiwiApi/qiwi/clients/wallet/methods/payment_by_details.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from glQiwiApi.core.abc.api_method import RuntimeValue
from glQiwiApi.qiwi.base import QiwiAPIMethod
from glQiwiApi.qiwi.clients.wallet.types import PaymentDetails, PaymentInfo, PaymentMethod
from glQiwiApi.types.amount import AmountWithCurrency
from glQiwiApi.types.amount import Amount


class MakePaymentByDetails(QiwiAPIMethod[PaymentInfo]):
Expand All @@ -20,7 +20,7 @@ class MakePaymentByDetails(QiwiAPIMethod[PaymentInfo]):
'fields': RuntimeValue(),
}

payment_sum: AmountWithCurrency = Field(..., scheme_path='sum')
payment_sum: Amount = Field(..., scheme_path='sum')
payment_method: PaymentMethod = Field(..., scheme_path='paymentMethod')
details: PaymentDetails = Field(..., scheme_path='fields')
payment_id: Optional[str] = Field(None, scheme_path='id')
2 changes: 1 addition & 1 deletion glQiwiApi/qiwi/clients/wallet/methods/predict_comission.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Any, ClassVar, Dict, Optional, Union
from typing import Any, ClassVar, Dict, Union

from pydantic import Field

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

from pydantic import Field

from glQiwiApi.core.abc.api_method import ReturningType
from glQiwiApi.core.session.holder import HTTPResponse
from glQiwiApi.qiwi.base import QiwiAPIMethod

Expand Down
4 changes: 1 addition & 3 deletions glQiwiApi/qiwi/clients/wallet/methods/reveal_card_id.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
from json import JSONDecodeError
from typing import Any, ClassVar

from pydantic import Field

from glQiwiApi.core.abc.api_method import Request, ReturningType
from glQiwiApi.core.abc.api_method import Request
from glQiwiApi.core.session.holder import HTTPResponse
from glQiwiApi.qiwi.base import QiwiAPIMethod
from glQiwiApi.qiwi.exceptions import QiwiAPIError

try:
from orjson import JSONDecodeError as OrjsonDecodeError
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import time
from typing import Any, ClassVar, Dict, Union
from typing import Any, ClassVar, Dict

from pydantic import Field

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

from pydantic import Field

from glQiwiApi.core.abc.api_method import ReturningType
from glQiwiApi.core.session.holder import HTTPResponse
from glQiwiApi.qiwi.base import QiwiAPIMethod

Expand Down
15 changes: 4 additions & 11 deletions glQiwiApi/qiwi/clients/wallet/types/account_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@
from datetime import datetime
from typing import Any, Dict, List, Optional, Union

from pydantic import Field, validator
from pydantic import Field

from glQiwiApi.types.amount import AmountWithCurrency, CurrencyModel
from glQiwiApi.types.amount import Amount, Currency
from glQiwiApi.types.base import Base
from glQiwiApi.utils.currency_util import Currency


class PassInfo(Base):
Expand Down Expand Up @@ -48,7 +47,7 @@ class AuthInfo(Base):
class SmsNotification(Base):
"""object: SmsNotification"""

price: AmountWithCurrency
price: Amount
enabled: bool
active: bool
end_date: Optional[datetime] = Field(None, alias='endDate')
Expand Down Expand Up @@ -95,7 +94,7 @@ class ContractInfo(Base):
class UserInfo(Base):
"""object: UserInfo"""

default_pay_currency: CurrencyModel = Field(..., alias='defaultPayCurrency')
default_pay_currency: Currency = Field(..., alias='defaultPayCurrency')
default_pay_source: Optional[int] = Field(None, alias='defaultPaySource')
default_pay_account_alias: Optional[str] = Field(None, alias='defaultPayAccountAlias')
email: Optional[str] = None
Expand All @@ -105,12 +104,6 @@ class UserInfo(Base):
phone_hash: str = Field(alias='phoneHash')
promo_enabled: Optional[bool] = Field(None, alias='promoEnabled')

@validator('default_pay_currency', pre=True)
def humanize_pay_currency(cls, v): # type: ignore
if not isinstance(v, int):
return v
return Currency.get(str(v))


class UserProfile(Base):
auth_info: Optional[AuthInfo] = Field(None, alias='authInfo')
Expand Down
Loading