Skip to content

Commit

Permalink
Merge pull request #2 from GLEF1X/synchronous
Browse files Browse the repository at this point in the history
0.2.13 pre_release
  • Loading branch information
GLEF1X committed Apr 20, 2021
2 parents cc4f52b + 294b477 commit 8a6f620
Show file tree
Hide file tree
Showing 43 changed files with 1,591 additions and 320 deletions.
38 changes: 19 additions & 19 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,21 @@
<img src="https://github.com/GLEF1X/glQiwiApi/blob/master/demo.gif"/>
</h2>

## :globe_with_meridians:Official api resources:
## 🌎Official api resources:

* :mortar_board:__Docs: [here](https://glqiwiapi.readthedocs.io/en/master/index.html)__
* 🎓__Docs: [here](https://glqiwiapi.readthedocs.io/en/master/index.html)__
* 🖱️ __Developer contacts: [![Dev-Telegram](https://img.shields.io/badge/Telegram-blue.svg?style=flat-square&logo=telegram)](https://t.me/GLEF1X)__

### :loudspeaker:New feature. Add YooMoney support and `pydantic` models to library!

### :floppy_disk:Installation
### 📣New feature. Add YooMoney support and `pydantic` models to library!
### 💾Installation

```bash
pip install glQiwiApi
```

---

## :bulb:Dependencies
## 🐦Dependencies

| Library | Description |
|:-------:|:----------------------------------------------:|
Expand All @@ -35,7 +34,7 @@ pip install glQiwiApi

---

## :pencil2:Dive-in Examples
## 🧸Dive-in Examples

```python
import asyncio
Expand Down Expand Up @@ -78,7 +77,7 @@ asyncio.run(main())

---

## :scroll:Checking transactions
## 🌀Checking transactions

```python
import asyncio
Expand All @@ -102,7 +101,7 @@ async def main():
asyncio.run(main())
```

## :city_sunset:Create & check p2p bills
## 🌱Create & check p2p bills

```python
import asyncio
Expand All @@ -113,7 +112,6 @@ 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(
public_p2p="your_p2p",
secret_p2p="your_secret_p2p"
) as w:
# Таким образом можно создать p2p счет
Expand All @@ -138,7 +136,7 @@ asyncio.run(main())

![form](https://i.ibb.co/T0C5RYz/2021-03-21-14-58-33.png)

## :rocket:Send to another wallet & get receipt(получение чека транзакции)
## Send to another wallet & get receipt(получение чека транзакции)

```python
import asyncio
Expand Down Expand Up @@ -168,7 +166,7 @@ asyncio.run(main())

```

## Send to card & check commission
## 💳Send to card & check commission

```python
import asyncio
Expand Down Expand Up @@ -198,7 +196,6 @@ asyncio.run(main())
```

## 🚀Query caching (beta)

```python
import asyncio

Expand Down Expand Up @@ -229,21 +226,21 @@ async def cache_test():
# Запросы ниже не будут браться из кэша,
# причиной тому есть разница в параметрах запроса
# Результат все также заноситься в кэш
print(len(await wallet.transactions(rows_num=30)) == 30) # True
print(len(await wallet.transactions(rows_num=30)) == 30) # True
# Однако, повторный запрос к апи будет выполнен, поскольку
# при попытке взятие результата из кэша валидатор сравнивает
# параметры запроса, если они не совпадают, то
# кэш игнорируется
# Повторный запрос к апи
print(len(await wallet.transactions(rows_num=10)) == 10) # True
print(len(await wallet.transactions(rows_num=10)) == 10) # True


asyncio.run(cache_test())


```

## :warning:Handling exceptions
## ⚠️Handling exceptions

```python
import asyncio
Expand All @@ -263,10 +260,14 @@ async def main():

asyncio.run(main())
```
---
## 🗺QIWI terminals
__glQiwiApi covers qiwi's MAPS api in QiwiMaps class__

# YooMoney API
---

# YooMoney API

## Important. How to get YooMoney access token

+ #### Регистрируем своё приложение в YooMoney по ссылке: [click](https://yoomoney.ru/myservices/new)
Expand Down Expand Up @@ -365,8 +366,7 @@ async def main():
amount=2
)
# Опционально, так вы можете проверить транзакцию, поступила ли она человеку на счёт
print(await w.check_transaction(amount=2, comment='I LOVE glQiwiApi',
transaction_type='out'))
print(await w.check_transaction(amount=2, comment='I LOVE glQiwiApi', transaction_type='out'))


asyncio.run(main())
Expand Down
4 changes: 1 addition & 3 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,7 @@
# The full version, including alpha/beta/rc tags.
release = glQiwiApi.__version__

releaselevel = 'dev' if parsed_version.dev else 'alpha' \
if 'a' in version else 'beta' \
if 'b' in version else 'stable'
releaselevel = 'beta'

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
Expand Down
4 changes: 3 additions & 1 deletion docs/examples/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,6 @@ Qiwi usage examples
p2p
basic_methods
usage_without_context
cache
cache
sync_support
usage_with_aiogram
10 changes: 10 additions & 0 deletions docs/examples/sync_support.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
=================
Synchronous usage
=================

*glQiwiApi* also coverage synchronous usage, you can use it like in the example

.. literalinclude:: ./../../examples/sync_usage.py
:caption: sync_usage.py
:language: python
:linenos:
8 changes: 8 additions & 0 deletions docs/examples/usage_with_aiogram.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
==================
Usage with aiogram
==================


.. literalinclude:: ./../../examples/usage_in_bots.py
:caption: usage_in_bots.py
:language: python
2 changes: 0 additions & 2 deletions examples/basic_methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,13 @@

TOKEN = "YOUR_API_ACCESS_TOKEN"
WALLET = "+NUMBER"
PUBLIC_KEY = 'YOUR_PUBLIC_P2P_TOKEN'
SECRET_KEY = 'YOUR_SECRET_P2P_TOKEN'


async def basic_usage():
async with QiwiWrapper(
api_access_token=TOKEN,
phone_number=WALLET,
public_p2p=PUBLIC_KEY,
secret_p2p=SECRET_KEY
) as wallet:
# Так вы можете получить информацию по транзакции, зная её айди и тип
Expand Down
9 changes: 4 additions & 5 deletions examples/p2p.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,24 @@

from glQiwiApi import QiwiWrapper, RequestError

PUBLIC_KEY = 'P2P PUBLIC_KEY'
SECRET_KEY = 'P2P SECRET_KEY'


async def p2p_usage():
async with QiwiWrapper(secret_p2p=SECRET_KEY, public_p2p=PUBLIC_KEY) as w:
async with QiwiWrapper(secret_p2p=SECRET_KEY) as w:
# bill id будет сгенерирован как str(uuid.uuid4()), если не был передан
bill = await w.create_p2p_bill(
amount=1,
comment='Im using glQiwiApi'
)
print(bill)
# Так можно проверить статус на оплаченный
status = (await w.check_p2p_bill_status(
status_1 = (await w.check_p2p_bill_status(
bill_id=bill.bill_id
)) == 'PAID'
# Или, начиная с версии 0.2.0
status = await bill.check()
print(status)
status_2 = await bill.check()
print(status_1 == status_2)
# Это выдаст ошибку, так как не передан api_access_token и phone_number
# Вы можете в любой момент переназначить токен или номер
try:
Expand Down
26 changes: 26 additions & 0 deletions examples/sync_usage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import datetime

from glQiwiApi import QiwiWrapper, sync

TOKEN = 'Api token from https://qiwi.com/api'
WALLET = '+phone_number'

# As always, we create an instance of the class,
# but pass on "without_context" as True
wallet = QiwiWrapper(
api_access_token=TOKEN,
phone_number=WALLET,
without_context=True # add this param to use sync connector soon
)


def sync_function() -> None:
start_date = datetime.datetime.now() - datetime.timedelta(days=5)
# Use the sync () function and pass the function we want to execute
# without calling it, that is, pass it as a regular variable
result = sync(wallet.transactions, rows_num=50, start_date=start_date,
end_date=datetime.datetime.now())
print(result)


sync_function()
50 changes: 50 additions & 0 deletions examples/usage_in_bots.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
from typing import Union

from aiogram import Bot, Dispatcher, types
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.dispatcher import FSMContext
from aiogram.utils import executor

from glQiwiApi import QiwiWrapper, types as qiwi_types

wallet = QiwiWrapper(
secret_p2p='YOUR_SECRET_P2P_TOKEN',
without_context=True
)

BOT_TOKEN = 'BOT_TOKEN'

bot = Bot(token=BOT_TOKEN, parse_mode=types.ParseMode.HTML)
storage = MemoryStorage()
dp = Dispatcher(bot, storage=storage)


async def create_payment(amount: Union[float, int] = 1) -> qiwi_types.Bill:
async with wallet:
return await wallet.create_p2p_bill(amount=amount)


@dp.message_handler(text='Хочу оплатить')
async def payment(message: types.Message, state: FSMContext):
bill = await create_payment()
await message.answer(
text=f'Хорошо, вот ваш счёт для оплаты:\n {bill.pay_url}'
)
await state.set_state('payment')
await state.update_data(bill=bill)


@dp.message_handler(state='payment', text='Оплатил')
async def successful_payment(message: types.Message, state: FSMContext):
async with state.proxy() as data:
bill: qiwi_types.Bill = data.get('bill')
status = await bill.check()
if status:
await message.answer('Вы успешно оплатили счет')
await state.finish()
else:
await message.answer('Счет не оплачен')


if __name__ == '__main__':
executor.start_polling(dp, skip_updates=True)
4 changes: 2 additions & 2 deletions examples/without_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@

from glQiwiApi import QiwiWrapper

# Создаем объект кошелька и обязательно передаем without_context = True, иначе будут проблемы с aiohttp.ClientSession
# Создаем объект кошелька и обязательно передаем without_context = True,
# иначе будут проблемы с aiohttp.ClientSession
wallet = QiwiWrapper(
api_access_token='token',
phone_number="+number",
public_p2p="your public_p2p token",
secret_p2p="your secret p2p",
without_context=True
)
Expand Down
33 changes: 24 additions & 9 deletions glQiwiApi/__init__.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,34 @@
import sys

from glQiwiApi.qiwi import QiwiWrapper
from glQiwiApi.utils.exceptions import RequestError, VersionError
from glQiwiApi.yoo_money import YooMoneyAPI
from glQiwiApi.utils import exceptions
from .qiwi import QiwiWrapper, QiwiMaps # NOQA
from .utils.basics import sync, to_datetime # NOQA
from .utils.exceptions import * # NOQA
from .yoo_money import YooMoneyAPI # NOQA

__all__ = (
(
'QiwiWrapper',
'YooMoneyAPI',
'QiwiMaps',
'RequestError',
'to_datetime',
'sync'
) + exceptions.__all__ # NOQA
)


class VersionError(Exception):
"""
Ошибка возникает, если ваша версия python не поддерживается библиотекой
"""

__all__ = [
'QiwiWrapper',
'YooMoneyAPI',
'RequestError'
]

if not sys.version_info[:2] >= (3, 7):
raise VersionError(
"Ваша версия python не поддерживается библиотекой glQiwiApi."
"Минимальная версия для использования python 3.7"
)

__version__ = '0.2.12'
__version__ = '0.2.13'
21 changes: 21 additions & 0 deletions glQiwiApi/core/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from .abstracts import (
AbstractParser,
AbstractCacheController,
AbstractPaymentWrapper,
AioTestCase
)
from .aiohttp_custom_api import CustomParser
from .basic_requests_api import HttpXParser, SimpleCache
from .mixins import BillMixin, ToolsMixin

__all__ = (
'HttpXParser',
'SimpleCache',
'AbstractParser',
'AbstractPaymentWrapper',
'AbstractCacheController',
'AioTestCase',
'BillMixin',
'ToolsMixin',
'CustomParser'
)
Loading

0 comments on commit 8a6f620

Please sign in to comment.