Skip to content

Commit

Permalink
Merge pull request #6 from GLEF1X/dev-1.0beta
Browse files Browse the repository at this point in the history
New version 1.0.0
  • Loading branch information
GLEF1X authored Jun 5, 2021
2 parents f9ea196 + 46e0800 commit 3e08bfa
Show file tree
Hide file tree
Showing 79 changed files with 3,087 additions and 2,565 deletions.
8 changes: 1 addition & 7 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,11 @@ __pycache__/
garbage.py
# C extensions
*.so
glQiwiApi/test2.py
test.py
web_test.py
bot
glQiwiApi/tranzoo
test2.py
setup.py
*/test.*
*.pem
glQiwiApi/webapp.py
glQiwiApi/templates
glQiwiApi/web
# Distribution / packaging
.Python
build/
Expand Down
54 changes: 25 additions & 29 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ pip install glQiwiApi
|aiofiles | saving receipts in pdf |
|uvloop | Optional(can boost API), but work only on Linux|
|pydantic | Json data validator. Very fast instead of custom|
|loguru | library which aims to bring enjoyable logging in Python|

---

Expand Down Expand Up @@ -116,23 +117,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.check()) # 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 Expand Up @@ -175,9 +176,9 @@ asyncio.run(main())
## 🌟Webhooks & handlers

```python
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 @@ -194,22 +195,16 @@ async def get_transaction(event: types.WebHook):
async def fetch_bill(notification: types.Notification):
print(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)
```

## 🧑🏻🔬Polling updates
## 🧑🏻🔬Polling updates
```python
import datetime

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

api_access_token = "your token"
phone_number = "your number"
Expand All @@ -229,7 +224,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
)
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

26 changes: 21 additions & 5 deletions docs/API.rst
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
.. currentmodule:: glQiwiApi

===
API
===
=============
API reference
=============

Payment wrappers
----------------
.. automodule:: glQiwiApi
:members: QiwiWrapper, YooMoneyAPI, QiwiMaps

QiwiWebhooks
Qiwi Webhooks
------------
.. automodule:: glQiwiApi.core.web_hooks.filter
:members:
Expand All @@ -21,6 +21,14 @@ QiwiWebhooks
:members:


.. _Executor overview:

Polling
-------
.. automodule:: glQiwiApi.utils.executor
:members:


Low level API
-------------
.. automodule:: glQiwiApi.core.basic_requests_api
Expand All @@ -31,12 +39,20 @@ Low level API

.. automodule:: glQiwiApi.core.storage
:members:



Aiogram integration
-------------------
.. automodule:: glQiwiApi.core.builtin.telegram
:members:


Synchronous adapter
-------------------
.. automodule:: glQiwiApi.utils.basics
:members: sync, _await_sync, _run_forever_safe


Exceptions
----------
.. automodule:: glQiwiApi.utils.exceptions
Expand Down
7 changes: 4 additions & 3 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
'sphinx.ext.autodoc',
'sphinx.ext.ifconfig',
"sphinx.ext.napoleon",
'sphinx.ext.autosectionlabel'
]

# Add any paths that contain templates here, relative to this directory.
Expand Down Expand Up @@ -130,15 +131,15 @@
# # The paper size ('letterpaper' or 'a4paper').
# #
# # 'papersize': 'letterpaper',

#
# # The font size ('10pt', '11pt' or '12pt').
# #
# # 'pointsize': '10pt',

#
# # Additional stuff for the LaTeX preamble.
# #
# # 'preamble': '',

#
# # Latex figure (float) alignment
# #
# # 'figure_align': 'htbp',
Expand Down
37 changes: 26 additions & 11 deletions docs/examples/qiwi/polling.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2,42 +2,57 @@
Polling updates
================

.. tip:: 👩🏻🎨 ``start_polling`` has the same signature as ``start_webhook``
.. tip:: 👩🏻🎨 ``start_polling`` has the same signature as ``start_webhook`` "under the hood"

👩🏻🔬This API method gives a chance to hook updates without webhooks on your machine,
👩🏻🔬This API method gives a chance to hook updates without webhooks on your machine,
but it's possible to use both approaches anyway.


🧑‍🎓 *First of all, before starting polling, you need to register handlers, just like when installing webhooks*
🧑🎓 *First of all, before starting polling, you need to register handlers, just like when installing webhooks.*
Lets do it with decorators, *but we also can do it another way, using* ``wallet.dispatcher.register_transaction_handler``

.. literalinclude:: ./../../../examples/qiwi/polling.py
:caption: Add handlers
:language: python
:emphasize-lines: 14-16
:emphasize-lines: 15-17

👨‍🔬 Then, you can start polling, but, let's make it clear which arguments you should pass on to ``start_polling`` method.
🧙♀️So, we also have to import ``executor`` :ref:`Executor overview` and pass on our client,
that contains user-friendly functions ``start_polling`` and ``start_webhook``.

.. literalinclude:: ./../../../examples/qiwi/polling.py
:caption: import executor module
:language: python
:emphasize-lines: 4, 24

👨🔬 Then, you can start polling, but, let's make it clear which arguments you should pass on to ``start_polling`` function.
So, in this example we see ``get_updates_from`` and ``on_startup``, it means, that in example we want to receive notifications that came an hour
ago and execute some function on startup of polling updates


.. literalinclude:: ./../../../examples/qiwi/polling.py
:caption: Args of polling
:language: python
:emphasize-lines: 23-26
:emphasize-lines: 26-27

😼 As you can see, in the example we have a function that we pass as an argument to ``on_startup``.

As you may have guessed, this function will be executed at the beginning of the polling.

.. literalinclude:: ./../../../examples/qiwi/polling.py
:caption: Args of polling
:language: python
:emphasize-lines: 19-20,25
:emphasize-lines: 20-21,27

😻 If you did everything correctly, you will get something like this

.. code-block:: bash
2021-05-13 16:27:22,921 - [INFO] - Start polling!
2021-05-13 16:27:22,922 - [INFO] - This message came on startup
2021-05-13 16:27:23,938 - [INFO] - Stop polling!
2021-06-05 17:21:07.423 | DEBUG | glQiwiApi.utils.executor:welcome:373 - Start polling!
🧚♀️ *Also, you can very easily implement simultaneous polling of updates from both aiogram and QIWI API.*

In the example below, we catch all text messages and return the same "Hello" response.

.. literalinclude:: ./../../../examples/qiwi/aiogram_integration.py
:caption: polling together with aiogram
:language: python
:emphasize-lines: 12-13,38,21-23,1-2,5,6
2 changes: 1 addition & 1 deletion examples/other/without_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
async def main():
bill = await wallet.create_p2p_bill(amount=1)
# new version
new_status = await bill.check()
new_status = await bill.paid
# old version
old_status = (await wallet.check_p2p_bill_status(bill.bill_id)) == 'PAID'
assert new_status == old_status
Expand Down
39 changes: 39 additions & 0 deletions examples/qiwi/aiogram_integration.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
from aiogram import Bot, Dispatcher
from aiogram import types

from glQiwiApi import QiwiWrapper
from glQiwiApi.core.builtin import TelegramPollingProxy
from glQiwiApi.types import Transaction
from glQiwiApi.utils import executor

api_access_token = "your token"
phone_number = "your number"

bot = Bot("token from BotFather")
dp = Dispatcher(bot)

wallet = QiwiWrapper(
api_access_token=api_access_token,
phone_number=phone_number
)


@dp.message_handler()
async def message_handler(msg: types.Message):
await msg.answer(text="Привет😇")


@wallet.transaction_handler()
async def my_first_handler(update: Transaction):
assert isinstance(update, Transaction)


def on_startup(wrapper: QiwiWrapper):
wrapper.dispatcher.logger.info("This message logged on startup")


executor.start_polling(
wallet,
on_startup=on_startup,
tg_app=TelegramPollingProxy(dp)
)
8 changes: 4 additions & 4 deletions examples/qiwi/p2p.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,19 @@ async def p2p_usage():
status_1 = (await w.check_p2p_bill_status(
bill_id=bill.bill_id
)) == 'PAID'
# Или, начиная с версии 0.2.0
status_2 = await bill.check()
# Или можно так(выглядит лаконичнее на мой взгляд)
status_2 = await bill.paid
print(status_1 == status_2)
# Это выдаст ошибку, так как не передан api_access_token и phone_number
# Вы можете в любой момент переназначить токен или номер
try:
await w.get_bills(rows=50)
await w.get_bills(rows_num=50)
except RequestError as ex:
print(ex)
# Переназначаем токены
w.api_access_token = 'TOKEN from https://qiwi.api'
w.phone_number = '+NUMBER'
print(await w.get_bills(rows=20))
print(await w.get_bills(rows_num=20))


asyncio.run(p2p_usage())
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
)
11 changes: 2 additions & 9 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 @@ -18,10 +17,4 @@ async def fetch_bill(notification: types.Notification):
print(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)
Loading

0 comments on commit 3e08bfa

Please sign in to comment.