Skip to content

Commit

Permalink
some changes in structure of api
Browse files Browse the repository at this point in the history
  • Loading branch information
GLEF1X committed Apr 6, 2021
1 parent 859f33d commit 11b396c
Show file tree
Hide file tree
Showing 18 changed files with 93 additions and 41 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
<h2 align="center">
<img src="https://cdn1.savepice.ru/uploads/2021/4/4/ca2c9284c789dfa15cb92a0f42f3e4ab-full.png" width="200"></img>
</h2>

[![PyPI version](https://img.shields.io/pypi/v/glQiwiApi.svg)](https://pypi.org/project/glQiwiApi/) [![Python](https://img.shields.io/badge/Python-3.7+-green)](https://www.python.org/downloads/) [![Code Quality Score](https://www.code-inspector.com/project/20780/score/svg)](https://frontend.code-inspector.com/public/project/20780/glQiwiApi/dashboard) ![Code Grade](https://www.code-inspector.com/project/20780/status/svg) ![Downloads](https://img.shields.io/pypi/dm/glQiwiApi)

Expand Down
2 changes: 1 addition & 1 deletion glQiwiApi/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from glQiwiApi.exceptions import RequestError
from glQiwiApi.utils.exceptions import RequestError
from glQiwiApi.qiwi import QiwiWrapper
from glQiwiApi.yoo_money import YooMoneyAPI

Expand Down
1 change: 0 additions & 1 deletion glQiwiApi/aiohttp_custom_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ async def _request(self, *args, **kwargs):
response = await super(CustomParser, self)._request(*args, **kwargs)
if response.status_code != 200:
self.raise_exception(str(response.status_code), json_info=response.response_data)

if self._without_context:
await self.session.close()

Expand Down
10 changes: 6 additions & 4 deletions glQiwiApi/mixins.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import copy
from typing import Optional, Any

from glQiwiApi.api import HttpXParser


class BillMixin(object):
"""
Примесь, позволяющая проверять счет, не используя метод QiwiWrapper,
добавляя метод check() объекту Bill
"""
_w = None
bill_id: Optional[str] = None

Expand All @@ -18,7 +20,7 @@ async def check(self) -> bool:


class ToolsMixin(object):
_parser: Optional[HttpXParser] = None
_parser = None

async def __aenter__(self):
"""Создаем сессию, чтобы не пересоздавать её много раз"""
Expand Down Expand Up @@ -48,5 +50,5 @@ def __deepcopy__(self, memo):
return result

@property
def parser(self) -> HttpXParser:
def parser(self):
return self._parser
22 changes: 9 additions & 13 deletions glQiwiApi/qiwi/basic_qiwi_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,18 +30,14 @@
}

QIWI_TO_CARD = WrapperData(
json=
{
json={
"id": str(int(time.time() * 1000)),
"sum":
{
"amount": "", "currency": "643"
},

"paymentMethod":
{
"type": "Account", "accountId": "643"
},
"sum": {
"amount": "", "currency": "643"
},
"paymentMethod": {
"type": "Account", "accountId": "643"
},
"fields": {
"account": ""
}
Expand Down Expand Up @@ -129,15 +125,15 @@
{"amount": "",
"currency": "643"
}
}
}
}}

COMMISSION_TRANSFER = {
'providerId': 'provider_id',
'withdrawSum': 'withdraw_sum',
'qwCommission': 'qw_commission',
'withdrawToEnrollmentRate': 'withdraw_to_enrollment_rate'
}

__all__ = (
'LIMIT_TYPES', 'TRANSACTION_TRANSFER', 'IDENTIFICATION_TRANSFER', 'QIWI_TO_WALLET', 'QIWI_TO_CARD',
'DEFAULT_QIWI_HEADERS', 'LIMIT_TYPES_TRANSFER', 'P2P_QIWI_HEADERS', 'P2P_DATA', 'P2P_BILL_TRANSFER',
Expand Down
26 changes: 24 additions & 2 deletions glQiwiApi/qiwi/qiwi_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@
import glQiwiApi.utils.basics as api_helper
from glQiwiApi.abstracts import AbstractPaymentWrapper
from glQiwiApi.aiohttp_custom_api import CustomParser
from glQiwiApi.utils.exceptions import InvalidData, InvalidCardNumber
from glQiwiApi.mixins import ToolsMixin
from glQiwiApi.qiwi.basic_qiwi_config import *
from glQiwiApi.qiwi.basic_qiwi_config import BASE_QIWI_URL, ERROR_CODE_NUMBERS, QIWI_TO_CARD, DEFAULT_QIWI_HEADERS, \
P2P_DATA, QIWI_TO_WALLET, ONLINE_COMMISSION_DATA, LIMIT_TYPES
from glQiwiApi.types import QiwiAccountInfo, Transaction, Bill, BillError, Statistic, Limit, Account, Balance, \
Identification, Response, Sum, Commission
from glQiwiApi.utils.exceptions import InvalidData, InvalidCardNumber

DEFAULT_BILL_TIME = datetime.now() + timedelta(days=2)

Expand Down Expand Up @@ -82,6 +83,7 @@ async def to_card(
except (KeyError, TypeError):
return response

@functools.lru_cache
async def _detect_card_number(self, card_number: str) -> str:
"""
Метод для получения идентификатора карты
Expand All @@ -107,6 +109,7 @@ async def _detect_card_number(self, card_number: str) -> str:
except KeyError:
raise InvalidCardNumber('Invalid card number or qiwi_types api is not response') from None

@functools.lru_cache
async def _detect_mobile_number(self, phone_number: str):
"""
Метод для получения идентификатора телефона
Expand All @@ -132,6 +135,7 @@ async def _detect_mobile_number(self, phone_number: str):
except KeyError:
raise InvalidCardNumber('Invalid card number or qiwi_types api is not response') from None

@functools.lru_cache
async def get_balance(self) -> Sum:
"""Метод для получения баланса киви"""
headers = self._auth_token(deepcopy(DEFAULT_QIWI_HEADERS))
Expand All @@ -143,6 +147,7 @@ async def get_balance(self) -> Sum:
):
return Sum.parse_raw(response.response_data['accounts'][0]['balance'])

@functools.lru_cache
async def transactions(
self,
rows_num: int = 50,
Expand Down Expand Up @@ -226,6 +231,7 @@ async def to_wallet(
except (KeyError, TypeError):
return response

@functools.lru_cache
async def transaction_info(
self,
transaction_id: Union[str, int],
Expand All @@ -252,6 +258,7 @@ async def transaction_info(
):
return Transaction.parse_raw(response.response_data)

@functools.lru_cache
async def check_restriction(self) -> Union[List[Dict[str, str]], Exception]:
"""
Метод для проверки ограничений на вашем киви кошельке\n
Expand All @@ -267,6 +274,7 @@ async def check_restriction(self) -> Union[List[Dict[str, str]], Exception]:
):
return response.response_data

@functools.lru_cache
async def get_identification(self) -> Identification:
"""
Функция, которая позволяет получить данные идентификации вашего киви кошелька
Expand All @@ -282,6 +290,7 @@ async def get_identification(self) -> Identification:
):
return Identification.parse_raw(response.response_data)

@functools.lru_cache
async def check_transaction(
self,
amount: Union[int, float],
Expand Down Expand Up @@ -320,6 +329,7 @@ async def check_transaction(
return True
return False

@functools.lru_cache
async def get_limits(self) -> Dict[str, Limit]:
"""
Функция для получения лимитов по счёту киви кошелька\n
Expand Down Expand Up @@ -349,6 +359,7 @@ async def get_limits(self) -> Dict[str, Limit]:
limits.update({code: Limit.parse_raw(limit[0])})
return limits

@functools.lru_cache
async def get_list_of_cards(self) -> dict:
"""
Данный метод позволяет вам получить список ваших карт. Пока ещё в разработке, стабильность сомнительна
Expand All @@ -362,6 +373,7 @@ async def get_list_of_cards(self) -> dict:
):
return response.response_data

@functools.lru_cache
async def authenticate(
self,
birth_date: str,
Expand Down Expand Up @@ -411,6 +423,7 @@ async def authenticate(
if response.ok and response.status_code == 200:
return {'success': True}

@functools.lru_cache
async def get_bills(self, rows: int) -> List[Bill]:
"""
Метод получения списка неоплаченных счетов вашего кошелька.
Expand All @@ -433,6 +446,7 @@ async def get_bills(self, rows: int) -> List[Bill]:
):
return api_helper.simple_multiply_parse(response.response_data.get("bills"), Bill)

@functools.lru_cache
async def create_p2p_bill(
self,
amount: int,
Expand Down Expand Up @@ -479,6 +493,7 @@ async def create_p2p_bill(
):
return Bill.parse_raw(response.response_data).initialize(self)

@functools.lru_cache
async def check_p2p_bill_status(self, bill_id: str) -> Literal['WAITING', 'PAID', 'REJECTED', 'EXPIRED']:
"""
Метод для проверки статуса p2p транзакции.\n
Expand All @@ -503,6 +518,7 @@ async def check_p2p_bill_status(self, bill_id: str) -> Literal['WAITING', 'PAID'
):
return Bill.parse_raw(response.response_data).status.value

@functools.lru_cache
async def reject_p2p_bill(self, bill_id: str) -> Bill:
"""
Метод для отмены транзакции.
Expand Down Expand Up @@ -553,6 +569,7 @@ async def get_receipt(
async with aiofiles.open(file_path + '.pdf', 'wb') as file:
return await file.write(response.response_data)

@functools.lru_cache
async def commission(self, to_account: str, pay_sum: Union[int, float]) -> Commission:
"""
Возвращается полная комиссия QIWI Кошелька за платеж в пользу указанного провайдера
Expand All @@ -575,6 +592,7 @@ async def commission(self, to_account: str, pay_sum: Union[int, float]) -> Commi
):
return Commission.parse_raw(response.response_data)

@functools.lru_cache
async def account_info(self) -> QiwiAccountInfo:
"""Метод для получения информации об аккаунте"""
headers = self._auth_token(deepcopy(DEFAULT_QIWI_HEADERS))
Expand Down Expand Up @@ -637,6 +655,7 @@ async def fetch_statistics(
):
return Statistic.parse_raw(response.response_data)

@functools.lru_cache
async def list_of_balances(self) -> List[Account]:
"""
Запрос выгружает текущие балансы счетов вашего QIWI Кошелька.
Expand All @@ -650,6 +669,7 @@ async def list_of_balances(self) -> List[Account]:
):
return api_helper.simple_multiply_parse(response.response_data.get('accounts'), Account)

@functools.lru_cache
@api_helper.allow_response_code(201)
async def create_new_balance(self, currency_alias: str) -> Optional[Dict[str, bool]]:
"""
Expand All @@ -670,6 +690,7 @@ async def create_new_balance(self, currency_alias: str) -> Optional[Dict[str, bo
):
return response.response_data

@functools.lru_cache
async def available_balances(self) -> List[Balance]:
"""
Запрос отображает псевдонимы счетов, доступных для создания в вашем QIWI Кошельке в виде списка объектов Balance
Expand All @@ -687,6 +708,7 @@ class Balance(BaseModel):
):
return api_helper.simple_multiply_parse(lst_of_objects=response.response_data, model=Balance)

@functools.lru_cache
@api_helper.allow_response_code(204)
async def set_default_balance(self, currency_alias: str) -> Any:
"""
Expand Down
23 changes: 19 additions & 4 deletions glQiwiApi/types/__init__.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,24 @@
from typing import Union, TypeVar, Callable, Any

from .basics import *
from .particular import *
from .qiwi_types import *
from .yoomoney_types import *
from .basics import (
Type, Sum, Commission, OptionalSum
)
from .particular import (Response, ProxyService, WrapperData, proxy_list)
from .qiwi_types import (
Bill,
BillError,
Statistic,
Balance,
Identification,
Limit,
Account,
QiwiAccountInfo,
Transaction
)
from .yoomoney_types import (
OperationType, OperationDetails, PreProcessPaymentResponse, Operation, Payment, IncomingTransaction, AccountInfo,
ALL_OPERATION_TYPES
)

BasicTypes = Union[
AccountInfo, Operation, OperationDetails,
Expand Down
2 changes: 1 addition & 1 deletion glQiwiApi/types/particular.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from aiohttp.typedefs import RawHeaders
from aiosocksy import Socks5Auth, Socks4Auth

from glQiwiApi.exceptions import ProxyError
from glQiwiApi.utils.exceptions import ProxyError


@dataclass
Expand Down
2 changes: 1 addition & 1 deletion glQiwiApi/types/qiwi_types/account.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from pydantic import BaseModel, Field

from glQiwiApi.types.basics import Sum, Type
from glQiwiApi.utils import custom_load
from glQiwiApi.utils.basics import custom_load


class Account(BaseModel):
Expand Down
2 changes: 1 addition & 1 deletion glQiwiApi/types/qiwi_types/account_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from pydantic import Field, BaseModel

from glQiwiApi.types.basics import Sum
from glQiwiApi.utils import custom_load
from glQiwiApi.utils.basics import custom_load


class PassInfo(BaseModel):
Expand Down
2 changes: 1 addition & 1 deletion glQiwiApi/types/qiwi_types/balance.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from pydantic import BaseModel

from glQiwiApi.utils import custom_load
from glQiwiApi.utils.basics import custom_load


class Balance(BaseModel):
Expand Down
2 changes: 1 addition & 1 deletion glQiwiApi/types/qiwi_types/bill.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

from glQiwiApi.types.basics import OptionalSum
from glQiwiApi.mixins import BillMixin
from glQiwiApi.utils import custom_load
from glQiwiApi.utils.basics import custom_load


class Customer(BaseModel):
Expand Down
2 changes: 1 addition & 1 deletion glQiwiApi/types/qiwi_types/identification.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from pydantic import BaseModel, Field

from glQiwiApi.utils import custom_load
from glQiwiApi.utils.basics import custom_load


class Identification(BaseModel):
Expand Down
2 changes: 1 addition & 1 deletion glQiwiApi/types/qiwi_types/limit.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from pydantic import BaseModel, Field

from glQiwiApi.utils import custom_load
from glQiwiApi.utils.basics import custom_load


class Interval(BaseModel):
Expand Down
2 changes: 1 addition & 1 deletion glQiwiApi/types/qiwi_types/stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from pydantic import BaseModel, Field

from glQiwiApi.types.basics import Sum
from glQiwiApi.utils import custom_load
from glQiwiApi.utils.basics import custom_load


class Statistic(BaseModel):
Expand Down
2 changes: 1 addition & 1 deletion glQiwiApi/types/qiwi_types/transaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from pydantic import BaseModel, Field

from glQiwiApi.types.basics import Sum
from glQiwiApi.utils import custom_load
from glQiwiApi.utils.basics import custom_load


class Provider(BaseModel):
Expand Down
Loading

0 comments on commit 11b396c

Please sign in to comment.